From 73a16f4561f3fdea289bad01acf436cc8090e23a Mon Sep 17 00:00:00 2001 From: Peter Chen Date: Thu, 30 Oct 2025 10:26:43 +0800 Subject: [PATCH] Add solution for "Binary Search" with unit tests. --- .../com/leetcode/easy/BinarySearch704.java | 31 ++++++++++++++++ .../leetcode/easy/BinarySearch704Test.java | 35 +++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 src/main/java/com/leetcode/easy/BinarySearch704.java create mode 100644 src/test/java/com/leetcode/easy/BinarySearch704Test.java diff --git a/src/main/java/com/leetcode/easy/BinarySearch704.java b/src/main/java/com/leetcode/easy/BinarySearch704.java new file mode 100644 index 0000000..e4df541 --- /dev/null +++ b/src/main/java/com/leetcode/easy/BinarySearch704.java @@ -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; + } +} diff --git a/src/test/java/com/leetcode/easy/BinarySearch704Test.java b/src/test/java/com/leetcode/easy/BinarySearch704Test.java new file mode 100644 index 0000000..eaef6ff --- /dev/null +++ b/src/test/java/com/leetcode/easy/BinarySearch704Test.java @@ -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); + } +}