首页 > 代码库 > 【LeetCode】26. Remove Duplicates from Sorted Array

【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消除重复的数字就好了

 1 class Solution(object):
 2     def removeDuplicates(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         l={i for i in nums}
 8         n=len(l)
 9         l = list(l)
10         l.sort()
11         nums=l
12         return n

 用C也挺简单的

 1 int removeDuplicates(int* nums, int numsSize) {
 2     int i=0,j=0;
 3     int flag=INT_MIN;
 4     for(i=0;i<numsSize;i++){
 5         if(nums[i]!=flag){
 6             nums[j]=nums[i];
 7             j++;
 8         }
 9         flag=nums[i];
10     }
11     return j;
12 }

 

【LeetCode】26. Remove Duplicates from Sorted Array