Skip to content

Commit 7cb6799

Browse files
committedSep 25, 2020
LeetCode 题解 1537, 1541
1 parent 969b3b8 commit 7cb6799

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
3+
final int MOD = (int) (1e9 + 7);
4+
5+
public int maxSum(int[] nums1, int[] nums2) {
6+
Set<Integer> set1 = Arrays.stream(nums1).boxed().collect(Collectors.toSet());
7+
Set<Integer> set2 = Arrays.stream(nums2).boxed().collect(Collectors.toSet());
8+
set1.retainAll(set2);
9+
if (set1.isEmpty()) {
10+
return (int) (Math.max(sum(nums1, 0, nums1.length - 1), sum(nums2, 0, nums2.length - 1))
11+
% MOD);
12+
}
13+
long res = 0;
14+
List<Integer> list = set1.stream().sorted(Comparator.naturalOrder())
15+
.collect(Collectors.toList());
16+
int start1 = 0, start2 = 0, end1 = 0, end2 = 0;
17+
for (int common : list) {
18+
// 2 个数组同时到达 set
19+
while (nums1[end1] != common) {
20+
end1++;
21+
}
22+
while (nums2[end2] != common) {
23+
end2++;
24+
}
25+
// max
26+
res += Math.max(sum(nums1, start1, end1), sum(nums2, start2, end2));
27+
start1 = end1 + 1;
28+
start2 = end2 + 1;
29+
}
30+
31+
res += Math.max(sum(nums1, end1 + 1, nums1.length - 1),
32+
sum(nums2, end2 + 1, nums2.length - 1));
33+
res %= MOD;
34+
return (int) res;
35+
}
36+
37+
private long sum(int[] n, int l, int r) {
38+
long res = 0;
39+
while (l <= r) {
40+
res += n[l++];
41+
}
42+
return res;
43+
}
44+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public int minInsertions(String s) {
3+
int left = 0;
4+
int res = 0;
5+
char[] chars = s.toCharArray();
6+
for (int i = 0; i < chars.length;) {
7+
if (chars[i] == '(') {
8+
left++;
9+
i++;
10+
} else {
11+
// 连续2个 )
12+
if (i < chars.length - 1 && chars[i + 1] == ')') {
13+
if (left > 0) {
14+
left--;
15+
} else {
16+
res++;
17+
}
18+
i += 2;
19+
} else {
20+
if (left > 0) {
21+
left--;
22+
res++;
23+
} else {
24+
res += 2;
25+
}
26+
i++;
27+
}
28+
}
29+
30+
}
31+
if (left > 0) {
32+
res += 2 * left;
33+
}
34+
return res;
35+
}
36+
}

0 commit comments

Comments
 (0)