Przeglądaj źródła

#feat:leetcode p35题题解

yangyi 2 tygodni temu
rodzic
commit
9ca0b3c37d
2 zmienionych plików z 75 dodań i 0 usunięć
  1. 29 0
      src/leetcode/p35/Solution.java
  2. 46 0
      src/leetcode/p35/SolutionTest.java

+ 29 - 0
src/leetcode/p35/Solution.java

@@ -0,0 +1,29 @@
+package leetcode.p35;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2026/3/9 15:15
+ * @Description: https://leetcode.cn/problems/search-insert-position/description/
+ * 35. 搜索插入位置
+ */
+public class Solution {
+    public int searchInsert(int[] nums, int target) {
+        int left = 0;
+        int right = nums.length - 1;
+        int mid = 0;
+
+        while (left < right) {
+            mid = (left + right) / 2;
+            if (target == nums[mid]) {
+                return mid;
+            }else if (target < nums[mid]) {
+                right = mid - 1;
+            }else {
+                left = mid + 1;
+            }
+        }
+        return target == nums[left] || target < nums[left]? left : left + 1;
+    }
+}

+ 46 - 0
src/leetcode/p35/SolutionTest.java

@@ -0,0 +1,46 @@
+package leetcode.p35;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: SolutionTest
+ * @Author: 杨逸
+ * @Data:2026/3/9 15:15
+ * @Description:
+ */
+@RunWith(Parameterized.class)
+public class SolutionTest {
+    public static final Solution solution = new Solution();
+    private final int[] nums;
+    private final int target;
+    private final int expected;
+
+    public SolutionTest(int[] nums, int target, int expected) {
+        this.nums = nums;
+        this.target = target;
+        this.expected = expected;
+    }
+    @Parameterized.Parameters
+    public static Collection<Object[]> data() {
+        return Arrays.asList(new Object[][]{
+            {new int[]{1,3,5,6},5,2},
+            {new int[]{1,3,5,6},2,1},
+            {new int[]{1,3,5,6},7,4},
+            {new int[]{1,3,5,6},0,0},
+        });
+    }
+
+    @Test
+    public void searchInsert() {
+        int result = solution.searchInsert(nums, target);
+        assertEquals(expected, result);
+    }
+}