首页 > 其他 > 详细

【LeetCode】26. Remove Duplicates from Sorted Array

时间:2016-12-24 14:15:16      阅读:214      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/fcyworld/p/6217141.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!