Skip to content

Commit bdd650b

Browse files
refactor 704
1 parent 10b5503 commit bdd650b

File tree

1 file changed

+23
-47
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+23
-47
lines changed
Lines changed: 23 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,29 @@
11
package com.fishercoder.solutions;
22

3-
/**
4-
* 704. Binary Search
5-
*
6-
* Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums.
7-
* If target exists, then return its index, otherwise return -1.
8-
*
9-
* Example 1:
10-
*
11-
* Input: nums = [-1,0,3,5,9,12], target = 9
12-
* Output: 4
13-
* Explanation: 9 exists in nums and its index is 4
14-
*
15-
* Example 2:
16-
*
17-
* Input: nums = [-1,0,3,5,9,12], target = 2
18-
* Output: -1
19-
* Explanation: 2 does not exist in nums so return -1
20-
*
21-
* Note:
22-
*
23-
* You may assume that all elements in nums are unique.
24-
* n will be in the range [1, 10000].
25-
* The value of each element in nums will be in the range [-9999, 9999].
26-
*/
273
public class _704 {
28-
public static class Solution1 {
29-
public int search(int[] nums, int target) {
30-
int left = 0;
31-
int right = nums.length - 1;
32-
if (target < nums[left] || target > nums[right]) {
33-
return -1;
34-
}
35-
if (nums[left] == target) {
36-
return left;
37-
} else if (nums[right] == target) {
38-
return right;
39-
}
40-
while (left <= right) {
41-
int mid = left + (right - left) / 2;
42-
if (target == nums[mid]) {
43-
return mid;
44-
} else if (target > nums[mid]) {
45-
left = mid + 1;
46-
} else {
47-
right = mid - 1;
4+
public static class Solution1 {
5+
public int search(int[] nums, int target) {
6+
int left = 0;
7+
int right = nums.length - 1;
8+
if (target < nums[left] || target > nums[right]) {
9+
return -1;
10+
}
11+
if (nums[left] == target) {
12+
return left;
13+
} else if (nums[right] == target) {
14+
return right;
15+
}
16+
while (left <= right) {
17+
int mid = left + (right - left) / 2;
18+
if (target == nums[mid]) {
19+
return mid;
20+
} else if (target > nums[mid]) {
21+
left = mid + 1;
22+
} else {
23+
right = mid - 1;
24+
}
25+
}
26+
return -1;
4827
}
49-
}
50-
return -1;
5128
}
52-
}
5329
}

0 commit comments

Comments
 (0)