I. Binary Search
#704. Binary Search (二分查找法原型代)
Recursive is easier to write and understand;
While loop is more complicated to write, but not easy to enter dead loop, and you'll impresive the interviewer because most interviewees prefer recursive.
If it's too complicated to code with while then use recursive to save time, otherwise use while.
class Solution{
public int binarySearch(int[] nums, int target){
int result = -1, start = 0, end = nums.length-1, mid;
if(num.length == 0){
return result;
}
while(start+1 < end){
mid = start + (end - start)/2;
if(target > nums[mid]){
start = mid;
}
else if(target < nums[mid]){
end = mid;
}
else{
result = mid;
break;
}
}
if(target == nums[start]){
result = start;
}
else if(target == nums[end]){
result = end;
}
return result;
}
}这个方法跳出while循环后,结果是left <= target <= right 或者target < left 或者target > right,并且确保如果数组里有重复的target,一定会被至少保留一个
这个方法只要跳出了while循环,结果是不管数组里有多少个重复的target,仅能迅速找到其中的一个,不是很通用
Binary search time complexity is , space comlexity is
There are two common coding:
while loop condition: left <= right, compare with target, the stop situation is left == right + 1
2. while loop condition: left < right, compare with right element, the stop condition is left == right. The example questions are: #162 PeakElement, #22 Search Rotated Array
Last updated
Was this helpful?