-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path954 Array of Doubled Pairs.py
80 lines (61 loc) · 1.6 KB
/
954 Array of Doubled Pairs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/python3
"""
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:
0 <= A.length <= 30000
A.length is even
-100000 <= A[i] <= 100000
"""
from typing import List
from collections import Counter
class Solution:
def canReorderDoubled(self, A: List[int]) -> bool:
A.sort(key=abs)
counter = Counter(A)
for a in A:
if counter[a] == 0:
continue
if counter[2*a] == 0:
return False
counter[a] -= 1
counter[2*a] -= 1
return True
def canReorderDoubled_positive_negative(self, A: List[int]) -> bool:
"""
sort + counter to form the doubled pairs
"""
A.sort()
counter = Counter(A)
for a in A:
if counter[a] == 0:
continue
counter[a] -= 1
if a > 0:
target = 2 * a
elif a % 2 != 0:
return False
else:
target = a // 2
if counter[target] > 0:
counter[target] -= 1
else:
return False
return True
if __name__ == "__main__":
assert Solution().canReorderDoubled([4,-2,2,-4]) == True