-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinarySearch.java
55 lines (46 loc) · 1.09 KB
/
BinarySearch.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.leetcode;
public class BinarySearch {
//https://leetcode.com/problems/binary-search/
class Solution {
public int search(int[] nums, int target) {
int n = nums.length;
int l = 0;
int r = n - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (nums[mid] < target) {
l = mid + 1;
} else {
r = mid - 1;
}
}
if (r != n - 1 && nums[r + 1] == target) return r + 1;
else return -1;
}
}
}
/**
while(l<=r){
int mid = l + (r-l)/2;
if(nums[mid] == target){
return mid;
}
if(nums[mid] < target){
l = mid+1;
}else{
r = mid -1;
}
}
**/
/**
while(l<r){
int mid = l + (r-l)/2;
if(nums[mid] < target){
l = mid+1;
}else{
r = mid;
}
}
if(nums[r] == target) return r;
else return -1;
**/