Bladeren bron

#feat:leetcode p3432题题解

yangyi 2 weken geleden
bovenliggende
commit
75c50d8f22
2 gewijzigde bestanden met toevoegingen van 60 en 0 verwijderingen
  1. 38 0
      src/leetcode/p3432/Solution.java
  2. 22 0
      src/leetcode/p3432/SolutionTest.java

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

@@ -0,0 +1,38 @@
+package leetcode.p3432;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2025/12/5 20:09
+ * @Description: https://leetcode.cn/problems/count-partitions-with-even-sum-difference/
+ * 3432. 统计元素和差值为偶数的分区方案
+ */
+class Solution {
+    public int countPartitions(int[] nums) {
+        {
+            //作者:灵茶山艾府
+            //链接:https://leetcode.cn/problems/count-partitions-with-even-sum-difference/solutions/3057701/nao-jin-ji-zhuan-wan-pythonjavacgo-by-en-sgu3/
+            //来源:力扣(LeetCode)
+            //著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
+            /**
+             * 脑筋急转弯做法,纯数学规律
+             */
+            //int s = Arrays.stream(nums).sum();
+            //return s % 2 != 0 ? 0 : nums.length - 1;
+        }
+        //前缀和做法
+        int[] prefix = new int[nums.length];
+        int ans = 0;
+        prefix[0] = nums[0];
+        for (int i = 1; i < nums.length; i++) {
+            prefix[i] = prefix[i - 1] + nums[i];
+        }
+        for (int i = 0; i < nums.length-1; i++) {
+            int left = prefix[i];
+            int right = prefix[nums.length - 1] - prefix[i];
+            if ((left - right) % 2 == 0) ans++;
+        }
+        return ans;
+    }
+}

+ 22 - 0
src/leetcode/p3432/SolutionTest.java

@@ -0,0 +1,22 @@
+package leetcode.p3432;
+
+import org.junit.Test;
+
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: SolutionTest
+ * @Author: 杨逸
+ * @Data:2025/12/5 20:13
+ * @Description: 
+ */
+public class SolutionTest {
+
+    @Test
+    public void countPartitions() {
+        Solution solution = new Solution();
+        int[] nums = new int[]{10,10,3,7,6};
+        int result = solution.countPartitions(nums);
+        System.out.println(result);
+    }
+}