二分查找
题目链接:二分查找
//二分查找,针对有序数组
var search = function(nums, target) {
this.nums = nums;
this.target = target;
var left = 0, right = nums.length;
while(left <= right) {
var mid = Math.floor((left + right)/2);
num = nums[mid];
if(nums[mid] == target) {
return mid;
} else if(nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return "missing";
}
var a = [1,2,3,4,5,6,7];
var b = +prompt("输入需要查询的数:");
document.write(search(a,b));
元素移除
题目链接:元素移除
//移除元素,双指针
var removeElement = function(nums, val) {
var left = 0, right = nums.length - 1;
while(left <= right) {
if(nums[left] != val) {
left = left + 1;
} else {
nums[left] = nums[right];
right = right - 1;
}
}
return right + 1;
};
var a = [1,2,2,4,5,6,7];
var b = +prompt("输入需要删除的数:");
document.write("最终的数组长度:"+removeElement(a,b));
心得体会
此系列博客仅用于督促自己好好刷题,水平有限,如有错误,欢迎留言讨论。谢谢大家嘿~