Title: Delete duplicate entries sorted array
Topic link: https: //leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
see this question, the first reaction is to direct violence:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int len = nums.size();
for(int i = 1; i < len; i++)
{
for(int j = 0; j < i; j++)
{
if(nums[j] == nums[i])
{
int k = i;
while(k < len - 1)
{
nums[k] = nums[k + 1];
k++;
}
len--;
i--;
break;
}
}
}
return len;
}
};
Although can be solved, but the speed is appalling.
After reading the official answer, I feel really very clever, speed really improved a lot:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int len = nums.size();
if(len == 0) return 0;
int i = 0;
for(int j = 1; j < len; j++)
{
if(nums[j] != nums[i])
{
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
};
Write when it ignores the input array is empty.
The road is long Come, happiness and earth!