LeetCode-C#实现-二分查找(#162/704)
162. Find Peak Element
山脉数组的峰顶索引
public class Solution { public int FindPeakElement(int[] nums) { int low=0,mid=0,high=nums.Length-1; while(low<high){ mid=(low+high)/2; if(nums[mid]>nums[mid+1])high=mid; else low=mid+1; } return low; } }
704. Binary Search
二分查找
public class Solution { public int Search(int[] nums, int target) { int low=0,mid=0,high=nums.Length-1; while(low<high){ mid=low+(high-low)/2;//防溢出 //不判断相等,使low,mid,high不断向target的索引靠近 if(nums[mid]<target) low=mid+1; else high=mid; } //若存在返回三者任一皆可,否则返回-1 return nums[low]==target?low:-1; } }