-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode704.java
More file actions
30 lines (28 loc) · 883 Bytes
/
LeetCode704.java
File metadata and controls
30 lines (28 loc) · 883 Bytes
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
public class LeetCode704 {
public static void main(String[] args) {
// 输入: nums = [-1,0,3,5,9,12], target = 9
// 输出: 4
System.out.println(new Solution704().search(new int[] { -1, 0, 3, 5, 9, 12 }, 9));
// 输入: nums = [-1,0,3,5,9,12], target = 2
// 输出: -1
System.out.println(new Solution704().search(new int[] { -1, 0, 3, 5, 9, 12 }, 2));
}
}
class Solution704 {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
return mid;
}
}
return -1;
}
}