954. 二倍数对数组(抄)
抽空好好看看。里面的语法我都看不懂。
class Solution {
public boolean canReorderDoubled(int[] arr) {
Map<Integer, Integer> cnts = new HashMap<>();
for(int num: arr)
cnts.put(num, cnts.getOrDefault(num, 0) + 1);
List<Integer> list = new ArrayList<>(cnts.keySet());
Collections.sort(list, (a, b) -> a - b);
for(int key: list) {
if(key > 0) {
if(cnts.getOrDefault(key * 2, 0) < cnts.get(key))
return false;
if(cnts.get(key) > 0)
cnts.put(key * 2, cnts.get(key * 2) - cnts.get(key));
} else if(key == 0) {
if(cnts.get(key) % 2 != 0)
return false;
}
else {
if(cnts.get(key) > 0 && (key % 2 != 0 || cnts.getOrDefault(key/2, 0) < cnts.get(key)))
return false;
if(cnts.get(key) > 0)
cnts.put(key / 2, cnts.get(key / 2) - cnts.get(key));
}
}
return true;
}
}
169. 多数元素(抄)
其实我并不是很理解。
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length >> 1];
}
}
剑指 Offer II 100. 三角形中最小路径之和
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int n = triangle.size();
int[][] f = new int[2][n];
f[0][0] = triangle.get(0).get(0);
for (int i = 1; i < n; ++i) {
int curr = i % 2;
int prev = 1 - curr;
f[curr][0] = f[prev][0] + triangle.get(i).get(0);
for (int j = 1; j < i; ++j) {
f[curr][j] = Math.min(f[prev][j - 1], f[prev][j]) + triangle.get(i).get(j);
}
f[curr][i] = f[prev][i - 1] + triangle.get(i).get(i);
}
int minTotal = f[(n - 1) % 2][0];
for (int i = 1; i < n; ++i) {
minTotal = Math.min(minTotal, f[(n - 1) % 2][i]);
}
return minTotal;
}
}