有点啰嗦。
这篇都是easy题,纪念刚开始刷题的日子,一直做嵌入式,根本不了解算法。
最开始刷的一题是remove duplicates,跟这个题一样的,都是用:
manage a new index to build array。
感叹一下,以前的同学早已经在AI领域大展拳脚,我还在这里从最简单的算法开始,安慰自己开始了就好吧。
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int index = 0;
for(auto num : nums)
{
if(num != 0)
{
nums[index++] = num;
}
}
for(; index < nums.size(); index++)
{
nums[index] = 0;
}
}
};
- Remove Duplicates from Sorted Array
https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int index = 0;
for(auto num : nums)
{
if(index < 1 || num != nums[index-1])
{
nums[index] = num;
index ++;
}
}
return index;
}
};
- Remove Duplicates from Sorted Array II
https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int index = 0;
for(auto num : nums)
{
if(index < 2 || num != nums[index-2])
{
nums[index++] = num;
}
}
return index;
}
};