构建类问题 constructive problem 2007,

2007. 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
class Solution {
    /**
    思路: sort array + map
    1. sort array
    2. 统计每个元素出现次数 map
    3. 遍历array,从map中判定其二倍数的进行消减
         1.如果map不存在,证明该数字已经被作为二倍消减
         2.如果map存在,但是二倍值不存在,那么不合法直接返回
     */
    public int[] findOriginalArray(int[] changed) {
        // 边界条件
        if(changed.length % 2 == 1) return new int[]{};
        // sort 数组
        Arrays.sort(changed);
        // 统计各元素数量
        Map<Integer, Integer> map = new HashMap<>();
        for(int e : changed) map.put(e, map.getOrDefault(e, 0) + 1);

        int[] result = new int[changed.length / 2];
        int index = 0 ;
        //从头开始扫描
        for(int key : changed) {
            // 如果不存在,可能已经作为二倍的值消掉了
            if(!map.containsKey(key)) continue;
            // 将key从count中--
            reduceCount(map, key);
            // 如果二倍的key不存在,那么说明不合法
            if(!map.containsKey(key * 2)) return new int[]{};
            // 将key * 2 从count中消掉
            reduceCount(map, key * 2);
            result[index++] = key;
        }
        return result;
    }

    private void reduceCount(Map<Integer, Integer> map, int key) {
        map.put(key, map.get(key) - 1);
        if(map.get(key) == 0) map.remove(key);
    }
}

 

posted @ 2024-03-03 04:16  xiaoyongyong  阅读(4)  评论(0编辑  收藏  举报