|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | import java.util.Arrays;
|
| 4 | +import java.util.Comparator; |
4 | 5 | import java.util.HashMap;
|
5 | 6 | import java.util.Map;
|
6 | 7 |
|
7 | 8 | public class _954 {
|
8 | 9 | public static class Solution1 {
|
| 10 | + /** |
| 11 | + * credit: https://leetcode.com/problems/array-of-doubled-pairs/solution/ |
| 12 | + */ |
9 | 13 | public boolean canReorderDoubled(int[] A) {
|
10 |
| - for (int i = 0; i < A.length; i++) { |
11 |
| - if (A[i] < 0) { |
12 |
| - A[i] = -A[i]; |
13 |
| - } |
14 |
| - } |
15 |
| - Arrays.sort(A); |
16 | 14 | Map<Integer, Integer> map = new HashMap<>();
|
17 |
| - for (int num : A) { |
18 |
| - map.put(num, map.getOrDefault(num, 0) + 1); |
| 15 | + for (int i : A) { |
| 16 | + map.put(i, map.getOrDefault(i, 0) + 1); |
19 | 17 | }
|
20 |
| - for (int num : A) { |
21 |
| - if (num != 0) { |
22 |
| - if (map.get(num) < 0) { |
23 |
| - return false; |
24 |
| - } else if (map.get(num) == 0) { |
25 |
| - continue; |
26 |
| - } else { |
27 |
| - int count = map.get(num); |
28 |
| - map.put(num, 0); |
29 |
| - int doubleNum = num * 2; |
30 |
| - if (!map.containsKey(doubleNum)) { |
31 |
| - return false; |
32 |
| - } else { |
33 |
| - map.put(doubleNum, map.get(doubleNum) - count); |
34 |
| - } |
35 |
| - } |
36 |
| - } else if (map.get(num) % 2 != 0) { |
| 18 | + Integer[] sorted = new Integer[A.length]; |
| 19 | + for (int i = 0; i < A.length; i++) { |
| 20 | + sorted[i] = A[i]; |
| 21 | + } |
| 22 | + Arrays.sort(sorted, Comparator.comparingInt(Math::abs)); |
| 23 | + for (int num : sorted) { |
| 24 | + if (map.get(num) == 0) { |
| 25 | + continue; |
| 26 | + } |
| 27 | + if (!map.containsKey(2 * num) || map.get(2 * num) <= 0) { |
37 | 28 | return false;
|
38 | 29 | }
|
| 30 | + map.put(num, map.get(num) - 1); |
| 31 | + map.put(2 * num, map.get(2 * num) - 1); |
39 | 32 | }
|
40 | 33 | return true;
|
41 | 34 | }
|
|
0 commit comments