Эх сурвалжийг харах

#feat:leetcode p74题题解

yangyi 2 долоо хоног өмнө
parent
commit
34c30f6d72

+ 49 - 0
src/leetcode/p74/Solution.java

@@ -0,0 +1,49 @@
+package leetcode.p74;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2026/3/9 17:52
+ * @Description: https://leetcode.cn/problems/search-a-2d-matrix/description/
+ * 74. 搜索二维矩阵
+ */
+public class Solution {
+    public boolean searchMatrix(int[][] matrix, int target) {
+        /**
+         * 二维数组的二分查找
+         */
+        int left1 = 0;
+        int left2 = 0;
+        int right1 = matrix.length - 1;
+        int right2 = matrix[0].length - 1;
+        int mid = 0;
+        //先找外围的数组
+        while(left1 < right1){
+            mid = (left1 + right1) / 2;
+            if (matrix[mid][0] > target) {
+                //在左边
+                right1 = mid - 1;
+            }else if (matrix[mid][right2] < target) {
+                //在右边
+                left1 = mid + 1;
+            }else {
+                //在中间数组里
+                left1 = mid;
+                right1 = mid;
+            }
+        }
+        //再找内层的数组
+        while(left2 < right2){
+            mid = (left2 + right2) / 2;
+            if (matrix[left1][mid] == target) {
+                return true;
+            }else if (matrix[left1][mid] > target) {
+                right2 = mid - 1;
+            }else {
+                left2 = mid + 1;
+            }
+        }
+        return target == matrix[left1][left2];
+    }
+}

+ 44 - 0
src/leetcode/p74/SolutionTest.java

@@ -0,0 +1,44 @@
+package leetcode.p74;
+
+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 18:01
+ * @Description:
+ */
+@RunWith(Parameterized.class)
+public class SolutionTest {
+    public static final Solution solution = new Solution();
+    private final int[][] matrix;
+    private final int target;
+    private final boolean expected;
+
+    public SolutionTest(int[][] matrix, int target, boolean expected) {
+        this.matrix = matrix;
+        this.target = target;
+        this.expected = expected;
+    }
+    @Parameterized.Parameters
+    public static Collection<Object[]> data(){
+        return Arrays.asList(new Object[][]{
+                {new int[][]{{1,3,5,7},{10,11,16,20},{23,30,34,60}},3,true},
+                {new int[][]{{1,3,5,7},{10,11,16,20},{23,30,34,60}},13,false},
+                {new int[][]{{1}},1,true},
+        });
+    }
+
+    @Test
+    public void searchMatrix() {
+        assertEquals(expected,solution.searchMatrix(matrix,target));
+    }
+}