704. Binary Search#
1 public int search(int[] nums, int target) {
2 int left = 0;
3 int right = nums.length - 1;
4
5 while (left <= right) {
6 int mid = left + (right - left) / 2;
7
8 if (nums[mid] == target) {
9 return mid;
10 } else if (nums[mid] < target) {
11 left = mid + 1;
12 } else if (nums[mid] > target) {
13 right = mid - 1;
14 }
15 return -1;
16 }
line no. 5:
<=
because we are taking right asnums.length - 1
line no. 6:
left + (right - left) / 2
instead of(left + right) / 2
for avoiding overflow.line no. 11:
mid + 1
asmid
has been checked already.line no. 13:
mid - 1
asmid
has been checked already.