[leetcode] Remove Duplicates from Sorted Array python

problem:


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 A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

solution:
class Solution:
    # @param a list of integers
    # @return an integer
    def removeDuplicates(self, A):
        if len(A) == 0:
            return 0
        n = len(A)
        index = 0
        for i in xrange(n):
            if A[index] != A[i]:
                index += 1
                A[index] = A[i]
        A = A[:index+1]
        return len(A)

解法二;

利用python数据结构set的去重功能,但是之后要对A排序。

class Solution:
    # @param a list of integers
    # @return an integer
    def removeDuplicates(self, A):
        A = list(set(A))
        A.sort()
        return len(A)   #注意题目要求 A 并不是乱序的 set(A)会导致在形成list后是乱序的



全部评论

相关推荐

二十岁的编程男神王大...:读博吧兄弟,你这绩点太好了,何必转码,另外哈哈哈真见到有括号标出来985的,这个不标注也知道吧
点赞 评论 收藏
分享
桌饺1:不是哥们儿,你学校有保研机会吗,这么高的绩点直接保研呗
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
05-13 20:37
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务