Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/main/java/com/leetcode/easy/BinarySearch704.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Tags: Array, Binary Search
package com.leetcode.easy;

public class BinarySearch704 {
/*
Let n be the size of the input array nums.

Time complexity: O(log n)
nums is divided into half each time.
In the worst-case scenario, we need to cut nums until the range has no element,
and it takes logarithmic time to reach this break condition.

Space complexity: O(1)
During the loop, we only need to record three indexes, left, right, and mid, they take constant space.
*/
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
} else if (target > nums[mid]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
35 changes: 35 additions & 0 deletions src/test/java/com/leetcode/easy/BinarySearch704Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.leetcode.easy;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class BinarySearch704Test {
private BinarySearch704 solution;

@BeforeEach
void setUp() {
solution = new BinarySearch704();
}

@Test
void testSearch_Example1() {
int[] nums = {-1, 0, 3, 5, 9, 12};
int target = 9;

int result = solution.search(nums, target);

assertEquals(4, result);
}

@Test
void testSearch_Example2() {
int[] nums = {-1, 0, 3, 5, 9, 12};
int target = 2;

int result = solution.search(nums, target);

assertEquals(-1, result);
}
}
Loading