Jelajahi Sumber

#feat:leetcode p80题题解

yangyi 2 minggu lalu
induk
melakukan
e983e8b24e
2 mengubah file dengan 80 tambahan dan 0 penghapusan
  1. 38 0
      src/leetcode/p80/Solution.java
  2. 42 0
      src/leetcode/p80/SolutionTest.java

+ 38 - 0
src/leetcode/p80/Solution.java

@@ -0,0 +1,38 @@
+package leetcode.p80;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2026/3/7 20:15
+ * @Description: https://leetcode.cn/problems/remove-duplicates-from-sorted-array-ii/description/?envType=study-plan-v2&envId=top-interview-150
+ * 80. 删除有序数组中的重复项 II
+ */
+public class Solution {
+    public int removeDuplicates(int[] nums) {
+        //记录当前值出现的次数
+        int count  = 1;
+        //记录当前值
+        int current = nums[0];
+        //记录要删除的个数,即需要移动的个数
+        int d = 0;
+        for (int i = 1; i < nums.length; i++) {
+            //是否需要向前移动
+            if (d != 0) {
+                nums[i-d] = nums[i];
+            }
+            //是否重复
+            if (nums[i] == current){
+                count++;
+                if(count > 2){
+                    d++;
+                }
+            }else {
+                //新值,重置
+                current = nums[i];
+                count = 1;
+            }
+        }
+        return nums.length - d;
+    }
+}

+ 42 - 0
src/leetcode/p80/SolutionTest.java

@@ -0,0 +1,42 @@
+package leetcode.p80;
+
+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/7 20:22
+ * @Description:
+ */
+@RunWith(Parameterized.class)
+public class SolutionTest {
+    public static final Solution solution = new Solution();
+    private int[] nums;
+    private int expected;
+
+    public SolutionTest(int[] nums, int expected) {
+        this.nums = nums;
+        this.expected = expected;
+    }
+    @Parameterized.Parameters
+    public static Collection<Object[]> data(){
+        return Arrays.asList(new Object[][] {
+                { new int[]{1,1,1,2,2,3}, 5 },
+                { new int[]{0,0,1,1,1,1,2,3,3}, 7 },
+        });
+    }
+
+    @Test
+    public void removeDuplicates() {
+        int result = solution.removeDuplicates(nums);
+        assertEquals("输入 " + Arrays.toString(nums) + " 时结果错误", expected, result);
+    }
+}