Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c27939d

Browse files
LeetCode problem: 704. Binary Search
1 parent 8db22c1 commit c27939d

File tree

3 files changed

+179
-0
lines changed

3 files changed

+179
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# 704. Binary Search
2+
3+
Difficulty: `Easy`
4+
Topics: `Array`, `Binary Search`
5+
6+
Given an array of integers `nums` which is sorted in ascending order, and an integer `target`, write a function to
7+
search `target` in `nums`. If `target` exists, then return its index. Otherwise, return `-1`.
8+
9+
You must write an algorithm with `O(log n)` runtime complexity.
10+
11+
**Example 1:**
12+
13+
```text
14+
Input: nums = [-1,0,3,5,9,12], target = 9
15+
Output: 4
16+
Explanation: 9 exists in nums and its index is 4
17+
```
18+
19+
**Example 2:**
20+
21+
```text
22+
Input: nums = [-1,0,3,5,9,12], target = 2
23+
Output: -1
24+
Explanation: 2 does not exist in nums so return -1
25+
```
26+
27+
**Constraints:**
28+
29+
- `1 <= nums.length <= 10^4`
30+
- `-10^4 < nums[i], target < 10^4`
31+
- All the integers in `nums` are unique.
32+
- `nums` is sorted in ascending order.
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.bl.binary_search;
2+
3+
/**
4+
* This is the solution to the LeetCode problem: 704. Binary Search
5+
*
6+
* @author Børre A. Opedal Lunde
7+
* @since 2024年01月27日
8+
*/
9+
public class Solution {
10+
11+
public int search(int[] nums, int target) {
12+
13+
int low = 0;
14+
int high = nums.length - 1;
15+
16+
// The loop will continue until the target is found or the low and high
17+
// indices have crossed each other. In which the target was not found.
18+
while (low <= high) {
19+
20+
// The reason why we don't use (low + high) / 2 is because it can
21+
// cause an integer overflow. For example:
22+
// low = 2 000 000 000
23+
// high = 2 000 000 000
24+
// low + high = 4 000 000 000 which is larger than the maximum
25+
// integer value: 2 147 483 647
26+
final int middleIndex = low + (high - low) / 2;
27+
final int middleValue = nums[middleIndex];
28+
29+
if (middleValue == target) {
30+
// The target was found, return its index.
31+
return middleIndex;
32+
} else if (middleValue > target) {
33+
// The target must be in the left half (lower half) of the array.
34+
high = middleIndex - 1;
35+
} else {
36+
// The target must be in the right half (upper half) of the array.
37+
low = middleIndex + 1;
38+
}
39+
}
40+
41+
// -1 represents that the target was not found.
42+
return - 1;
43+
}
44+
}
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
package com.bl.binary_search;
2+
3+
import org.junit.jupiter.api.DisplayName;
4+
import org.junit.jupiter.api.Test;
5+
6+
import static org.junit.jupiter.api.Assertions.assertEquals;
7+
import static org.junit.jupiter.api.Assertions.assertTrue;
8+
9+
/**
10+
* This is the test to the LeetCode problem: 704. Binary Search
11+
*
12+
* @author Børre A. Opedal Lunde
13+
* @since 2024年01月27日
14+
*/
15+
@DisplayName("Binary Search")
16+
class SolutionTest {
17+
18+
private final Solution solution = new Solution();
19+
20+
@Test
21+
@DisplayName("Example one")
22+
void exampleOne() {
23+
int[] nums = {- 1, 0, 3, 5, 9, 12};
24+
int target = 9;
25+
26+
int expected = 4;
27+
int actual = solution.search(nums, target);
28+
29+
assertEquals(expected, actual);
30+
}
31+
32+
@Test
33+
@DisplayName("Example two")
34+
void exampleTwo() {
35+
int[] nums = {- 1, 0, 3, 5, 9, 12};
36+
int target = 2;
37+
38+
int expected = - 1;
39+
int actual = solution.search(nums, target);
40+
41+
assertEquals(expected, actual);
42+
}
43+
44+
@Test
45+
@DisplayName("Empty array should return -1")
46+
void emptyArrayShouldReturn1() {
47+
int[] nums = {};
48+
int target = 9; // Doesn't matter what the target is.
49+
50+
int expected = - 1;
51+
int actual = solution.search(nums, target);
52+
53+
assertEquals(expected, actual);
54+
}
55+
56+
@Test
57+
@DisplayName("Target is a negative number")
58+
void targetIsANegativeNumber() {
59+
int[] nums = {- 1, 0, 3, 5, 9, 12};
60+
int target = - 1;
61+
62+
int expected = 0;
63+
int actual = solution.search(nums, target);
64+
65+
assertEquals(expected, actual);
66+
}
67+
68+
@Test
69+
@DisplayName("Target is larger than the largest number in the array")
70+
void targetIsLargerThanTheLargestNumberInTheArray() {
71+
int[] nums = {- 1, 0, 3, 5, 9, 12};
72+
int target = 13;
73+
74+
int expected = - 1;
75+
int actual = solution.search(nums, target);
76+
77+
assertEquals(expected, actual);
78+
}
79+
80+
@Test
81+
@DisplayName("Target is smaller than the smallest number in the array")
82+
void targetIsSmallerThanTheSmallestNumberInTheArray() {
83+
int[] nums = {- 1, 0, 3, 5, 9, 12};
84+
int target = - 2;
85+
86+
int expected = - 1;
87+
int actual = solution.search(nums, target);
88+
89+
assertEquals(expected, actual);
90+
}
91+
92+
@Test
93+
@DisplayName("All elements in the array are the same")
94+
void allElementsInTheArrayAreTheSame() {
95+
int[] nums = {1, 1, 1, 1, 1, 1};
96+
int target = 1;
97+
98+
int actual = solution.search(nums, target);
99+
100+
// The actual index is not important, as long as it's a valid index.
101+
assertTrue(actual >= 0 && nums[actual] == target);
102+
}
103+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /