vlambda博客
学习文章列表

二分查找leetcode题目

  1. (162 medium) 寻找峰值

    var findPeakElement = function(nums) { if(nums.length===0)return 0; let L=0 let R=nums.length-1 while(L<R){ let mid=parseInt((L+R)/2) if(nums[mid]>nums[mid+1]){ R=mid }else{ L=mid+1 } } return L};
  2. (240 medium) 搜索二维矩阵2


    var searchMatrix = function(matrix, target) { let m=matrix.length if(m==0)return false let n=matrix[0].length let x=n-1 let y=0 while(x>=0&&y<m){ let cur=matrix[y][x] if(cur===target)return true if(cur>target){ x-- }else{ y++ } } return false};

3.(275 medium) h指数2

       

var hIndex = function(citations) { let l=0,r=citations.length; while(l<r){ let mid=Math.ceil(l+r+1>>1); if(citations[citations.length-mid]>=mid) l=mid; else r=mid-1; } return l;};

4.(441 easy) 排列硬币

var arrangeCoins = function(n) { let left=0 let right=n while(left<=right){ let mid=Math.floor((left+right)/2) let cost=mid*(mid+1)/2 if(cost===n){ return mid }else if(cost<n){ left=mid+1 }else if(cost>n){ right=mid-1 } } return right};

5.(704 easy) 二分查找

var search = function(nums, target) { let left = 0; let right = nums.length-1; let mid; while(left <= right){ mid = parseInt((left+right)/2); let midVal = nums[mid]; if(midVal === target) return mid; if(midVal > target) right=mid-1; if(midVal < target) left=mid+1; } return -1;};

6.(744 easy )寻找比目标字母大的最小字母

var search = function(nums, target) { let left = 0; let right = nums.length-1; let mid; while(left <= right){ mid = parseInt((left+right)/2); let midVal = nums[mid]; if(midVal === target) return mid; if(midVal > target) right=mid-1; if(midVal < target) left=mid+1; } return -1;};