在3020. 子集中元素的最大数量【力扣周赛 382】用哈希表统计元素个数使用
点击查看代码- class Solution {
- public int maximumLength(int[] nums) {
- Map<Long, Integer> cnt = new HashMap<>();
- for (int x : nums) {
- cnt.merge((long) x, 1, Integer::sum);
- }
- // while true:
- Integer c1 = cnt.remove(1L);
- int ans = c1 != null ? c1 - 1 | 1 : 0;
- // 奇数-1为偶数,跟1取或后加1;偶数减1为奇数,或运算后不变(答案必须为奇数)
- for (long x : cnt.keySet()) {
- int res = 0;
- for (; cnt.getOrDefault(x, 0) > 1; x *= x) {
- res += 2;
- }
- res = res + (cnt.containsKey(x) ? 1 : -1);
- ans = Math.max(ans, res);
- }
- return ans;
- }
- }
复制代码 感谢灵神,灵神题解,还使用了keySet()方法
merge()
点击查看代码- String k = "key";
- HashMap<String, Integer> map = new HashMap<String, Integer>() {{
- put(k, 1);
- }};
- map.merge(k, 2, (oldVal, newVal) -> oldVal + newVal);
复制代码 等价于:点击查看代码- String k = "key";
- HashMap<String, Integer> map = new HashMap<String, Integer>() {{
- put(k, 1);
- }};
- Integer newVal = 2;
- if(map.containsKey(k)) {
- map.put(k, map.get(k) + newVal);
- } else {
- map.put(k, newVal);
- }
复制代码 jdk8源码和注释
点击查看代码[code] @Override public V merge(K key, V value, BiFunction |