Find Original Array From Doubled Array

An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array.

Given an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order.

Example 1:

Input: changed = [1,3,4,2,6,8]
Output: [1,3,4]
Explanation: One possible original array could be [1,3,4]:
- Twice the value of 1 is 1 * 2 = 2.
- Twice the value of 3 is 3 * 2 = 6.
- Twice the value of 4 is 4 * 2 = 8.
Other original arrays could be [4,3,1] or [3,1,4].

Example 2:

Input: changed = [6,3,0,1]
Output: []
Explanation: changed is not a doubled array.

Example 3:

Input: changed = [1]
Output: []
Explanation: changed is not a doubled array.

Constraints:

  • 1 <= changed.length <= 105
  • 0 <= changed[i] <= 105

思路:// 正着扫描完之后,判断0,很难判断;
            // 反着扫描,这样就是高位先遇见记录下来;好处就是比正着扫描好判断;
            // 碰见element的时候,hashmap里面有twice,就去掉twice,element啥也不做。
            // 如果没有遇见twice,就加入element频率; 

class Solution {
    public int[] findOriginalArray(int[] changed) {
        int n = changed.length;
        if(n % 2 != 0) {
            return new int[]{};
        }
        Arrays.sort(changed);
        int[] res = new int[n / 2];
        int index = 0;
        HashMap<Integer, Integer> hashmap = new HashMap<>();
        for(int j = n - 1; j >= 0; j--) {
            int element = changed[j];
            int twice = 2 * element;
            // 正着扫描完之后,判断0,很难判断;
            // 反着扫描,这样就是高位先遇见记录下来;好处就是比正着扫描好判断;
            // 碰见element的时候,hashmap里面有twice,就去掉twice,element啥也不做。
            // 如果没有遇见twice,就加入element频率;
            if(hashmap.containsKey(twice)) {
                if(hashmap.get(twice) == 1) {
                    hashmap.remove(twice);
                }else {
                    hashmap.put(twice, hashmap.get(twice) - 1);
                }
                res[index++] = element;
            } else {
                // !hashmap.containsKey(twice);
                hashmap.put(element, hashmap.getOrDefault(element, 0) + 1);
            }
        }
        return index == n / 2 ? res : new int[]{};
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值