Skip to content

Commit eb32257

Browse files
committed
day 11
1 parent 8677bb3 commit eb32257

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*
2+
Array of Doubled Pairs
3+
======================
4+
5+
Given an integer array of even length arr, return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2, or false otherwise.
6+
7+
Example 1:
8+
Input: arr = [3,1,3,6]
9+
Output: false
10+
11+
Example 2:
12+
Input: arr = [2,1,2,6]
13+
Output: false
14+
15+
Example 3:
16+
Input: arr = [4,-2,2,-4]
17+
Output: true
18+
Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].
19+
20+
Example 4:
21+
Input: arr = [1,2,4,16,8,4]
22+
Output: false
23+
24+
Constraints:
25+
2 <= arr.length <= 3 * 104
26+
arr.length is even.
27+
-105 <= arr[i] <= 105
28+
*/
29+
30+
class Solution
31+
{
32+
public:
33+
bool canReorderDoubled(vector<int> &arr)
34+
{
35+
36+
map<int, int> nums;
37+
for (auto &i : arr)
38+
nums[i]++;
39+
40+
while (nums.size() > 0)
41+
{
42+
int least = (*nums.begin()).first;
43+
int target;
44+
45+
if (least == 0)
46+
{
47+
if (nums[least] % 2 != 0)
48+
return false;
49+
nums.erase(least);
50+
}
51+
52+
else
53+
{
54+
55+
if (least < 0)
56+
{
57+
if (least % 2 != 0)
58+
return false;
59+
target = least / 2;
60+
}
61+
else
62+
target = 2 * least;
63+
64+
int mi = min(nums[target], nums[least]);
65+
if (mi == 0)
66+
return false;
67+
68+
nums[target] -= mi;
69+
nums[least] -= mi;
70+
71+
if (!nums[target])
72+
nums.erase(target);
73+
if (!nums[least])
74+
nums.erase(least);
75+
}
76+
}
77+
return true;
78+
}
79+
};

Leetcode Daily Challenge/August-2021/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,5 @@
1212
| 7. | [Palindrome Partitioning II](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/613/week-1-august-1st-august-7th/3872/) | [cpp](./07.%20Palindrome%20Partitioning%20II.cpp) |
1313
| 9. | [Add Strings](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/614/week-2-august-8th-august-14th/3875/) | [cpp](./09.%20Add%20Strings.cpp) |
1414
| 10. | [Flip String to Monotone Increasing](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/614/week-2-august-8th-august-14th/3876/) | [cpp](./10.%20Flip%20String%20to%20Monotone%20Increasing.cpp) |
15+
| 11. | [Array of Doubled Pairs](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/614/week-2-august-8th-august-14th/3877/) | [cpp](./11.%20Array%20of%20Doubled%20Pairs.cpp) |
1516
| 12. | [Group Anagrams](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/614/week-2-august-8th-august-14th/3887/) | [cpp](./12.%20Group%20Anagrams.cpp) |

0 commit comments

Comments
 (0)