二分查找leetcode题目

Posted Flydeft日记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二分查找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;};


以上是关于二分查找leetcode题目的主要内容,如果未能解决你的问题,请参考以下文章

算法专题(01)二分查找(01) 简单LeetCode 704

算法入门 02二分查找(简单 - 第四题)LeetCode 167

⭐算法入门⭐《二分枚举》中等02 —— LeetCode 面试题 10.09. 排序矩阵查找

算法专题(01)二分查找(03) 简单LeetCode 278

LeetCode刷题704-简单-二分查找

LeetCode刷题704-简单-二分查找