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.
Key point:
start + 1 < end (防止死循环)
mid = start + (end-start)/2
A[mid] =, < , >
A[start] A[end] ? target
classSolution{publicintbinarySearch(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; }elseif(target < nums[mid]){ end = mid; }else{ result = mid;break; } }if(target == nums[start]){ result = start; }elseif(target == nums[end]){ result = end; }return result; }}
while loop condition: left <= right, compare with target, the stop situation is left == right + 1
// Some code
left = 0
right = len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
if nums[mid] > target:
right = mid - 1
else:
left = mid + 1
return -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
// Some code
left = 0
right = len(nums) - 1
while left < right:
mid = left + (right - left) // 2
if nums[mid] < nums[right]
left = mid + 1
else:
right = mid
return left // or return right