基本查找
循环顺序查找
二分查找与分治
分治:分而治之。把复杂的问题分成两个或更多相同的子问题。直到最后子问题可以简单的直接求解,原问题的解即子问题的解的合并。
-
循环
public int binarySearch(int[] array,int low,int high,int target){ while(low<=high){ //int mid=(low+high)/2; //除的效率非常低,一般用移位来代替 //int mid = (low+high) >> 1; //假如low和high很大,low+high可能会溢出 //int mid = low + (high - low)>>1;错误的,>>的优先级低于 +- //=》 (low+(high-low))>>1 int mid = low + ((high-low)>>1); if(array[mid] == target){ return mid; } else if(array[mid] > target){ high = mid-1; } else { low = mid + 1; } } }
-
递归
public int binarySearch1(int[] array,int low,int high,int target){ if(low<=high){ int mid = low + ((high-low)>>1); if(array[mid] == target){ return mid; } else if(array[mid] > target){ return binarySearch(array,low,mid-1,target); } else { return binarySearch(array,mid+1,high,target); } } }
元素中有重复的二分查找
如果要重复找左侧第一个
找到了目标值,左移,直到找到左侧第一个。
满足条件就左移。
找到0了,不能左移,直接返回mid。
public static int search(int[] nums,int target){ if(num==null || nums.length == 0){ return -1; } int left = 0; int right = nums.length-1; while(left<=right){ int mid = left+(right-left)/2; if(nums[mid]<target){ left = mid+1; } else if(nums[mid]>target){ right = mid-1; } else { while(mid != 0 &&nums[mid]==target){ mid--; } if(mid == 0 && nums[mid]==target){ return mid; } return mid+1; } } return -1; }