realhaidinh
Senior Member
C++:
class Solution {
public:
int minOperations(vector<int>& nums) {
cin.tie(0); cout.tie(0); ios::sync_with_stdio(0);
unordered_map<int, int> cnt;
for(int& num : nums)
cnt[num]++;
int n3, n2, res = 0;
for(auto& [num, occ] : cnt) {
n3 = occ / 3;
if(occ % 3 == 2)
res += n3 + (occ - n3 * 3) / 2;
else if(occ % 3 == 1) {
n3--;
n2 = (occ - n3 * 3) / 2;
if(n3 < 0 || n3 * 3 + n2 * 2 != occ)
return - 1;
res += n3 + n2;
}
else
res += n3;
}
return res;
}
};

. O(1) space ảo thiệt
ngồi 1 lúc thấy tận dụng đc cái đống index của array để làm 0(1)
nhiều bài hard sẽ làm được nếu ko bỏ cuộc
toàn kiến thức chuyên tin
