[LeetCode]26. Remove Duplicates from Sorted Array

  要求原位去重排序,返回nums的length并用nums的引用来检查排序,非常无聊的字符操作 不如来一发深拷贝吧~233

 

  

Success
Details 
Runtime: 92 ms, faster than 90.98% of Python3 online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 15.6 MB, less than 5.74% of Python3 online submissions for Remove Duplicates from Sorted Array.
Next challenges:
 

Submission Detail

161 / 161 test cases passed.
Status: 

Accepted

Runtime: 92 ms
Memory Usage: 15.6 MB
Submitted: 3 minutes ago

 

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        length = len(nums)
        # 0 1
        if length == 0 or length == 1:
            return length
        #normal
        nums[:] = list(set(nums))
        nums.sort()
        return len(nums)

 

80ms:

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        i, j = 0, 1
        l = len(nums)
        while j < l:
            if nums[i] == nums[j]:
                j+=1
            else:
                i+=1
                nums[i] = nums[j]
        return i+1

 

14M:

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if len(nums) == 0:
            return 0
        n_pre = len(nums)
        cnt = 0
        cur = nums[0]
        i = 1
        while i < len(nums):
            if nums[i] == cur:
                nums.pop(i)
                cnt += 1
            else:
                cur = nums[i]
                i += 1
        return n_pre - cnt

 

posted @ 2019-08-09 14:35  夜歌乘年少  阅读(283)  评论(1编辑  收藏  举报