ReZero's Utopia.

Algo tips

Word count: 112Reading time: 1 min
2020/08/10 Share
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int binarySearch(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
// 注意
while(left <= right) {
int mid = left + (right - left) / 2;
if(nums[mid] == target)
return mid;
else if (nums[mid] < target)
left = mid + 1;
// 注意
else if (nums[mid] > target)
right = mid - 1; // 注意 }
return -1;
}
  1. 为什么 while 循环的条件中是 <=,⽽不是 <
  • 因为初始化 right 的赋值是 nums.length - 1 ,即最后一个元素的索引,而不是nums.length
  • 防止漏掉 [a, a] 区间
CATALOG
  1. 1. Binary Search