This article summarizes some of the binary search variants, most of which come from Leetcode
1. (leetcode) Search in rotated Sorted Array
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Public intSearchint[] Nums,intkey) { intLo =0, hi = nums.length-1; while(Lo <=hi) { intMid = lo + (hi-lo)/2; if(Nums[mid] = = key)returnmid; if(Nums[mid] < Nums[hi]) {//right Half ordered if(Nums[mid] < key && Key <=Nums[hi]) {Lo= Mid +1;//key falls in the ordered part}Else{//Otherwise the key falls in the unordered partHi = Mid-1; } }Else{//left half ordered if(Nums[lo] <= key && Key <Nums[mid]) {Hi= Mid-1;//key falls in the ordered part}Else{//Otherwise the key falls in the unordered partLo = mid +1; } } } return-1; }
View Code
2. (Leetcode Bayi) Search in rotated Sorted Array II
(i.e. 1 2 4 4 4 4 4 might become 4 4 4 1 2 4 4).
//about the last nums[mid] = = nums [Hi] Situation//1 2 1) 1 1//l m H-hi--; //1 2 1) 1 1//l m H PublicBoolean Search (int[] Nums,inttarget) { if(NULL= = Nums | | Nums.length <0)return false; intLo =0, hi = nums.length-1; while(Lo <=hi) { intMid = lo + (hi-lo)/2; //Get It if(Nums[mid] = = target)return true; //find an ordered section to find if(Nums[mid] < Nums[hi]) {//The second part is ordered if(Nums[mid] < target && Target <=Nums[hi]) {Lo= Mid +1; }Else{Hi= Mid-1; } }Else if(Nums[mid] > Nums[hi]) {//first half ordered if(Nums[lo] <= target && Target <Nums[mid]) {Hi= Mid-1; } Else{lo= Mid +1; } }Else{//Nums[mid] = = Nums[hi]Hi-- ; } } return false; }
View Code
3. Find Minimum in rotated Sorted Array
In the rotated array, find the smallest number
If NUMS[MID] > Nums[hi] min falls in [Mid+1, HI]
If NUMS[MID] < Nums[hi] min falls on [0, Mid]
Public intFindmin (int[] nums) { intLo =0, hi = nums.length-1; while(Lo <hi) { intMid = lo + (hi-lo)/2 ; //mid > Hi,min in [Mid+1,hi] if(Nums[mid] >Nums[hi]) {Lo= Mid +1; } //Mid < Hi, min in [0,mid] if(Nums[mid] <Nums[hi]) {Hi=mid; } } returnNums[lo]; }
View Code
4. Find Minimum in rotated Sorted Array II
Same as the last topic, but with a repetition, the same as the idea of topic 1-2
If NUMS[MID] > Nums[hi] min falls in [Mid+1, HI]
If NUMS[MID] < Nums[hi] min falls on [0, Mid]
If nums[mid] = = Nums[hi] Then make further judgments after hi--
Public intFindmin (int[] nums) { intLo =0, hi = nums.length-1; while(Lo <hi) { intMid = lo + (hi-lo)/2; if(Nums[mid] >Nums[hi]) {Lo= Mid +1; }Else if(Nums[mid] <Nums[hi]) {Hi=mid; }Else{Hi--; } } returnNums[lo]; }
View Code
Two-point Search