26. Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums = [1,1,2]
,
Your function should return length = 2
, with the first two elements of nums being 1
and 2
respectively. It doesn't matter what you leave beyond the new length.
26.从有序数组中移除重复元素
给定一个有序数组,就地移除重复元素使得每个元素只出现一次并且返回新的数组长度。
不要分配额外的内存来创建另外的数组,你必须使用固定内存就地完成。
举例:
给定数组nums=[1,1,2]
你的函数应该返回length=2,而且nums的前两个元素分别应该是1和2。超过新数组长度的部分你就不用管了。
思路:因为是有序数组,所以每遇到一个新值时暂存然后继续向后遍历,如果等于这个值就跳过,不等于时就要更新新值。所有的新值依次保存在原数组中,因为新值的数量肯定小于等于原数组元素的数组,所以这样覆盖保存并不会出问题。
int removeDuplicates(int* nums, int numsSize) {
if (numsSize == 0) return 0;
int len = numsSize;
int index = 1;
int t = nums[0];
for (int i = 1; i < numsSize; i++){
if (nums[i] != t){
nums[index++] = nums[i];
t = nums[i];
}
else{
len--;
}
}
return len;
}
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums: return 0
length,index,t = len(nums),1,nums[0]
for i in nums[1:]:
if i != t:
nums[index] = i
index += 1
t = i
else:
length -= 1
return length