Directory link:
Likou Programming Questions-Solution Summary_Sharing + Recording-CSDN Blog
GitHub synchronous question brushing project:
https://github.com/September26/java-algorithms
Original title link:LeetCode official website - the technology growth platform loved by geeks around the world
describe:
gives you an integer array with subscripts starting from 0 nums
, if the following conditions are met, It is considered that the array nums
is a beautiful array :
nums.length
is an even number- For all subscripts that satisfy
i % 2 == 0
, is truei
nums[i] != nums[i + 1]
Note that empty arrays are also considered beautiful arrays.
You can remove any number of elements from nums
. When you delete an element, all elements to the right of the deleted element will move one unit to the left to fill the gap, while the elements on the left will remain unchanged< a i=3>.
Returns the minimum number of elements that need to be deleted to make nums
a beautiful array < a i=4>.
Example 1:
Input:nums = [1,1,2,3,5] Output: 1 Explanation: can be deletednums[0]
ornums[1]
to get < a i=8> = [1,2,3,5] is a beautiful array. It can be proved that in order to make nums into a beautiful array, at least 1 element needs to be deleted.nums
Example 2:
Input:nums = [1,1,2,2,3,3] Output: 2 Explanation: can deletenums[0]
andnums[5]
, so that the obtained nums = [1, 2,2,3] is a beautiful array. It can be proved that in order to make nums into a beautiful array, at least 2 elements need to be deleted.
hint:
1 <= nums.length <= 105
0 <= nums[i] <= 105
Problem-solving ideas:
The length of nums is 10^5, so the time complexity of this question is O(n) to O(n*logn).
In fact, we can traverse the array from the beginning and record the current status.
index represents the traversed position, postion represents the traversed position after deletion, lastValue represents the value of the last even-numbered digit after deletion, and deleteNum represents the number of deletions. If position is an even number, record the value and modify the positions of index and position. If position is an odd number of digits, determine whether it is equal to lastValue and modify index and deleteNum.
Code:
class Solution {
public:
int minDeletion(vector<int> &nums)
{
int deleteNum = 0;
int index = 0;
int position = 0;
int lastValue = -1;
while (index < nums.size())
{
if (position % 2 == 0)
{
lastValue = nums[index];
index++;
position++;
continue;
}
if (lastValue == nums[index])
{
index++;
deleteNum++;
continue;
}
index++;
position++;
}
if (position % 2 != 0)
{
deleteNum++;
}
return deleteNum;
}
};