[LeetCode] 954. Array of Doubled Pairs

Given an array of integers A with even length, return true if and only if it is possible to reorder it such that A[2 * i + 1] = 2 * A[2 * i] for every 0 <= i < len(A) / 2.

 

Example 1:

Input: [3,1,3,6]
Output: false

Example 2:

Input: [2,1,2,6]
Output: false

Example 3:

Input: [4,-2,2,-4]
Output: true
Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].

Example 4:

Input: [1,2,4,16,8,4]
Output: false

Note:

  1. 0 <= A.length <= 30000
  2. A.length is even
  3. -100000 <= A[i] <= 100000

If the input array is not sorted, then it is difficult to know for A[2 * i], whether it should be used to match A[2 * i + 1] = 2 * A[2 * i] or A[2 * i] = 2 * A[2 * i - 1]. But if we sort the input array, it makes this matching process easier as shown in the following.

For all the sorted negative integers, start to match from smallest to largest; (-4 < -2)

For all the sorted positive integers, start to match from smallest to largest; (2 < 4)

When following the above match order, we know that in order to be able to make this array a complete doubled pairs, if there are m of integer a, then there must be at least m of integer 2 * a(for a >= 0) or a /2 (for a < 0).

As a result, we need a fast way to keep all the counts of unused integers, a hint for hash map. The keys would be all the integers and the values are the frequencies of these integers. Combined with the need of having all integers in sorted order, we use TreeMap.

The runtime is O(N * logN), constructing the tree map is the dominant part of the runtime.

 1 class Solution {
 2     public boolean canReorderDoubled(int[] A) {
 3         if(A.length == 0) {
 4             return true;
 5         }
 6         Map<Integer, Integer> counts = new TreeMap<>();
 7         for(int a : A) {
 8             counts.put(a, counts.getOrDefault(a, 0) + 1);
 9         }
10         for(int a : counts.keySet()) {
11             //if the counts of a is 0, it means we've already used all a to do matching, skip
12             if(counts.get(a) == 0) {
13                 continue;
14             }
15             if(a < 0) {
16                 if(counts.get(a) > counts.getOrDefault(a / 2, 0)) {
17                     return false;
18                 }
19                 counts.put(a / 2, counts.get(a / 2) - counts.get(a));
20             }
21             else {
22                 if(counts.get(a) > counts.getOrDefault(a * 2, 0)) {
23                     return false;
24                 }
25                 counts.put(a * 2, counts.get(a * 2) - counts.get(a));                
26             }
27         }
28         return true;
29     }
30 }
原文地址:https://www.cnblogs.com/lz87/p/10096256.html