You are given an array arranged in ascending ordernums
. Please delete the repeated elements in place so that each element appears only once and return the new length of the array after deletion. The relative order of elements should remain consistent . Then return nums
the number of unique elements in .
Considering nums
the number of unique elements is k
, you need to do the following to ensure that your solution can be passed:
- Changes the array
nums
so thatnums
the previousk
element of contains unique elements,nums
arranged in the order in which they originally appeared in .nums
The size of the remaining elementsnums
does not matter. - return
k
26. Remove duplicates in ordered array - LeetCode
My solution to the problem:
// 推导过程 (双指针)
|
0,0,1,1,1,2,2,3,3,4
|
|
0,0,1,1,1,2,2,3,3,4
|
|
0,1,1,1,1,2,2,3,3,4
|
|
0,1,1,1,1,2,2,3,3,4
|
|
0,1,1,1,1,2,2,3,3,4
|
|
0,1,2,1,1,2,2,3,3,4
|
|
0,1,2,1,1,2,2,3,3,4
|
|
0,1,2,3,1,2,2,3,3,4
|
|
0,1,2,3,1,2,2,3,3,4
|
|
0,1,2,3,1,2,2,3,3,4
|
|
0,1,2,3,4,2,2,3,3,4
|
My code:
// 26. 删除有序数组中的重复项 (请你 原地 删除重复出现的元素)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int i=0,j=1;
if(nums.size()==0) return 0;
if(nums.size() == 1) return 1;
for(;i<nums.size() && j<nums.size();) {
while(j < nums.size() && (nums[i] == nums[j])) {
j++;
}
++i;
if(i<nums.size() && j<nums.size())
nums[i] = nums[j];
}
return i;
}
};
Simplify code
// 简化
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()==0) return 0;
int p=0,q=1;
while(q < nums.size()) {
if(nums[p]!=nums[q]) {
nums[p+1] = nums[q];
p++;
}
q++;
}
return p+1;
}
};
Official code:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
if (n == 0) {
return 0;
}
int fast = 1, slow = 1;
while (fast < n) {
if (nums[fast] != nums[fast - 1]) {
nums[slow] = nums[fast];
++slow;
}
++fast;
}
return slow;
}
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/remove-duplicates-from-sorted-array/solutions/728105/shan-chu-pai-xu-shu-zu-zhong-de-zhong-fu-tudo/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Complexity analysis
Time complexity: O(n)O(n)O(n), where nnn is the length of the array. The fast pointer and slow pointer can each move at most nnn times.
Space complexity: O(1)O(1)O(1). Just need to use the extra space of the constant