【LeetCode】26. Remove Duplicates from Sorted Array

时间:2023-03-09 00:52:21
【LeetCode】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.

题意:消除数组中所有重复的数字,重复数字只留一个

这样的题用Python好简单啊

直接用集合set消除重复的数字就好了

 class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l={i for i in nums}
n=len(l)
l = list(l)
l.sort()
nums=l
return n

用C也挺简单的

 int removeDuplicates(int* nums, int numsSize) {
int i=,j=;
int flag=INT_MIN;
for(i=;i<numsSize;i++){
if(nums[i]!=flag){
nums[j]=nums[i];
j++;
}
flag=nums[i];
}
return j;
}