Merge pull request #2870 from curforever/master

修改leetcode-master\problems\kamacoder\0044.开发商购买土地.md Java版本、修改leetcode-master\problems\0349.两个数组的交集.md Java版本
This commit is contained in:
程序员Carl
2025-01-13 10:03:57 +08:00
committed by GitHub
2 changed files with 16 additions and 4 deletions

View File

@ -123,6 +123,9 @@ public:
### Java ### Java
版本一使用HashSet 版本一使用HashSet
```Java ```Java
// 时间复杂度O(n+m+k) 空间复杂度O(n+k)
// 其中n是数组nums1的长度m是数组nums2的长度k是交集元素的个数
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
@ -145,8 +148,15 @@ class Solution {
} }
//方法1将结果集合转为数组 //方法1将结果集合转为数组
return res.stream().mapToInt(Integer::intValue).toArray();
return resSet.stream().mapToInt(x -> x).toArray(); /**
* 将 Set<Integer> 转换为 int[] 数组:
* 1. stream() : Collection 接口的方法,将集合转换为 Stream<Integer>
* 2. mapToInt(Integer::intValue) :
* - 中间操作,将 Stream<Integer> 转换为 IntStream
* - 使用方法引用 Integer::intValue将 Integer 对象拆箱为 int 基本类型
* 3. toArray() : 终端操作,将 IntStream 转换为 int[] 数组。
*/
//方法2另外申请一个数组存放setRes中的元素,最后返回数组 //方法2另外申请一个数组存放setRes中的元素,最后返回数组
int[] arr = new int[resSet.size()]; int[] arr = new int[resSet.size()];
@ -538,3 +548,4 @@ end
<a href="https://programmercarl.com/other/kstar.html" target="_blank"> <a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/> <img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a> </a>

View File

@ -212,13 +212,14 @@ public class Main {
int horizontalCut = 0; int horizontalCut = 0;
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
horizontalCut += horizontal[i]; horizontalCut += horizontal[i];
result = Math.min(result, Math.abs(sum - 2 * horizontalCut)); result = Math.min(result, Math.abs((sum - horizontalCut) - horizontalCut));
// 更新result。其中horizontalCut表示前i行的和sum - horizontalCut表示剩下的和作差、取绝对值得到题目需要的“A和B各自的子区域内的土地总价值之差”。下同。
} }
int verticalCut = 0; int verticalCut = 0;
for (int j = 0; j < m; j++) { for (int j = 0; j < m; j++) {
verticalCut += vertical[j]; verticalCut += vertical[j];
result = Math.min(result, Math.abs(sum - 2 * verticalCut)); result = Math.min(result, Math.abs((sum - verticalCut) - verticalCut));
} }
System.out.println(result); System.out.println(result);