二分查找
题目链接:https://leetcode.cn/problems/binary-search/
文章讲解:https://programmercarl.com/0704.%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE.html
视频讲解:https://www.bilibili.com/video/BV1fA4y1o715
核心在于边界值的确定
左闭右闭区间
//实现左闭右闭区间的写法 ``` var search = function(nums, target) { let left = 0; let right = nums.length - 1; while (left <= right) { let mid = Math.floor((right + left) / 2) if(nums[mid] > target) { right = mid - 1;//左区间查找 }else if(nums[mid] < target) { left = mid + 1;//右区间查找 }else{ return mid; } } return -1; }; ```左闭右开区间
//实现左闭右开区间的写法 var search = function(nums, target) { let left = 0; let right = nums.length;//右边界本身是取不到的,所以下标我们这里设置为nums.length while (left < right) { let mid = Math.floor((right + left) / 2) if(nums[mid] > target) { right = mid;//左区间查找 }else if(nums[mid] < target) { left = mid + 1;//右区间查找 }else{ return mid; } } return -1; };移除元素
题目链接:https://leetcode.cn/problems/remove-element/
文章讲解:https://programmercarl.com/0027.%E7%A7%BB%E9%99%A4%E5%85%83%E7%B4%A0.html
视频讲解:https://www.bilibili.com/video/BV12A4y1Z7LP
javascript中本身没有双指针的概念,实现移除元素比较简单,就是常说的数组去重
var removeElement = function(nums, val) { let k = 0; for(let i = 0; i < nums.length; i++) { if(nums[i] !== val) { nums[k++] = nums[i] } } return k; }; 标签:right,LeetCode704,nums,随想录,length,let,https,移除 From: https://www.cnblogs.com/xxdj168/p/17220379.html