954. 二倍数对数组(抄)

抽空好好看看。里面的语法我都看不懂。

  1. class Solution {
  2. public boolean canReorderDoubled(int[] arr) {
  3. Map<Integer, Integer> cnts = new HashMap<>();
  4. for(int num: arr)
  5. cnts.put(num, cnts.getOrDefault(num, 0) + 1);
  6. List<Integer> list = new ArrayList<>(cnts.keySet());
  7. Collections.sort(list, (a, b) -> a - b);
  8. for(int key: list) {
  9. if(key > 0) {
  10. if(cnts.getOrDefault(key * 2, 0) < cnts.get(key))
  11. return false;
  12. if(cnts.get(key) > 0)
  13. cnts.put(key * 2, cnts.get(key * 2) - cnts.get(key));
  14. } else if(key == 0) {
  15. if(cnts.get(key) % 2 != 0)
  16. return false;
  17. }
  18. else {
  19. if(cnts.get(key) > 0 && (key % 2 != 0 || cnts.getOrDefault(key/2, 0) < cnts.get(key)))
  20. return false;
  21. if(cnts.get(key) > 0)
  22. cnts.put(key / 2, cnts.get(key / 2) - cnts.get(key));
  23. }
  24. }
  25. return true;
  26. }
  27. }

169. 多数元素(抄)

其实我并不是很理解。

  1. class Solution {
  2. public int majorityElement(int[] nums) {
  3. Arrays.sort(nums);
  4. return nums[nums.length >> 1];
  5. }
  6. }

剑指 Offer II 100. 三角形中最小路径之和

  1. class Solution {
  2. public int minimumTotal(List<List<Integer>> triangle) {
  3. int n = triangle.size();
  4. int[][] f = new int[2][n];
  5. f[0][0] = triangle.get(0).get(0);
  6. for (int i = 1; i < n; ++i) {
  7. int curr = i % 2;
  8. int prev = 1 - curr;
  9. f[curr][0] = f[prev][0] + triangle.get(i).get(0);
  10. for (int j = 1; j < i; ++j) {
  11. f[curr][j] = Math.min(f[prev][j - 1], f[prev][j]) + triangle.get(i).get(j);
  12. }
  13. f[curr][i] = f[prev][i - 1] + triangle.get(i).get(i);
  14. }
  15. int minTotal = f[(n - 1) % 2][0];
  16. for (int i = 1; i < n; ++i) {
  17. minTotal = Math.min(minTotal, f[(n - 1) % 2][i]);
  18. }
  19. return minTotal;
  20. }
  21. }