思路:贪心。
贪心思路:当有重复元素时,尽量让第一个处在下标为奇数的位置,如果必须为偶数,只能删掉一个,从左向右遍历,得到的就是ans数组。
具体思路:如果ans数组元素个数tol为偶数时直接放,否则放跟ans末尾最后一个元素不一样的。如果最终ans中有奇数个元素,则tol–才为ans最终的个数
class Solution {
public:
int minDeletion(vector<int>& nums) {
int n = nums.size();
int tol = 0, cur = -1;
for (auto& a : nums) {
if (tol % 2 == 0) {
cur = a;
tol++;
}else if (a != cur){
tol++;
cur = a;
}
}
if (tol & 1) tol--;
return n - tol;
}
};