LeetCode 2007. 从双倍数组中还原原数组

题目链接

https://leetcode.cn/problems/find-original-array-from-doubled-array/description/?envType=daily-question&envId=2024-04-18

先给数组排序,然后使用hashmap来标记元素是双倍之前还是之后的

class Solution {
    public int[] findOriginalArray(int[] changed) {
        Arrays.sort(changed);
        int[] ans = new int[changed.length / 2];
        int j = 0;
        Map<Integer, Integer> map = new HashMap<>();
        for (int i=0;i<changed.length;i++) {
            int x = changed[i];
            if (!map.containsKey(x)) { //当前元素x不是双倍后的
                if (j == ans.length) {
                    return new int[0];
                }
                ans[j] = x;
                j++;
                map.merge(x * 2, 1, Integer::sum); //标记
            } else { //当前元素x是双倍后的
                int c = map.merge(x, -1, Integer::sum); //清除标记
                if (c == 0) {
                    map.remove(x);
                }
            }
        }
        return ans;
    }
}

相关推荐

  1. 2007. 数组还原数组

    2024-04-23 09:10:02       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-23 09:10:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-23 09:10:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-23 09:10:02       87 阅读
  4. Python语言-面向对象

    2024-04-23 09:10:02       96 阅读

热门阅读

  1. LRU缓存(哈希+双链表)

    2024-04-23 09:10:02       44 阅读
  2. Spring Cloud 面试题(七)

    2024-04-23 09:10:02       36 阅读
  3. 在 Oracle 数据库中使用正则表达式

    2024-04-23 09:10:02       37 阅读
  4. 【Web前端笔记14】函数与对象

    2024-04-23 09:10:02       36 阅读
  5. IDM激活_powershelll

    2024-04-23 09:10:02       33 阅读
  6. MyBatis 面试题(六)

    2024-04-23 09:10:02       30 阅读
  7. IDM的实用功能

    2024-04-23 09:10:02       32 阅读
  8. markdown语法转换成html渲染到页面

    2024-04-23 09:10:02       40 阅读
  9. MongoDB的UTCDateTime如何使用

    2024-04-23 09:10:02       34 阅读