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 by modifying the input array in-place with O(1) extra memory.

Example:

Given 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.
 class Solution {
public:
int removeDuplicates(vector<int>& a) {
if(a.size()==) return ;
int i = ;
int j = ; for (;j < a.size();++j) {
if(a[i]!=a[j]) {
i++;
}
a[i] = a[j];
}
return i+;
}
};

与删除排序链表中的重复元素类似,利用排序的特性,如果后一个元素大于当前元素,则不是重复的数字

 class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)< 2:
return len(nums)
j = 0
for i in range(1,len(nums)):
if(nums[i]>nums[j]):
j+=1
nums[j]=nums[i] return j+1

20180507

 class Solution {
public int removeDuplicates(int[] nums) {
int m = 0;
for(int i = 0;i<nums.length;i++){
if(m<1||nums[i]>nums[m-1])
nums[m++] = nums[i];
}
return m;
}
}
上一篇:深入了解一下PYTHON中关于SOCKETSERVER的模块-C


下一篇:026 Remove Duplicates from Sorted Array 从排序数组中删除重复项