26. Remove Duplicates from Sorted Array

题目链接

 

 思路一:单指针法,遍历数组,遇到和下一个元素不同的把这个元素按顺序保存到数组的前面,用指针记录保存的个数,注意数组只有一个元素和遍历到最后俩元素的特殊情况。

class Solution:
    def removeDuplicates(self,nums):
        sum = 0
        if len(nums) <= 1:
            return 1
        for i in range(len(nums)-1):
            if i == (len(nums)-2):
                if nums[i] != nums[i+1]:
                    nums[sum] = nums[i]
                    nums[sum+1] = nums[i+1]
                    sum +=2

                else:
                    nums[sum] = nums[i]
                    sum +=1
            else:
                if nums[i] != nums[i+1]:
                    nums[sum] = nums[i]
                    sum +=1
        nums = nums[:sum]
        return sum
if __name__ == '__main__':#提交时main函数内容不用带上
    nums = [1]
    solution = Solution()
    print(solution.removeDuplicates(nums))

思路二,双指针和思路一大同小异

 1 class Solution:
 2     def removeDuplicates(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         if len(nums) <= 1:
 8             return len(nums)
 9         i = 0
10         j = 1
11         while (j < len(nums)):
12             if nums[i] == nums[j]:
13                 nums.pop(j)
14             else:
15                 j = j + 1
16                 i = j - 1
17         return len(nums)

 思路三:使用set,但是貌似开辟空间了,但是在力扣也通过了

1 class Solution:
2     def removeDuplicates(self, nums):
3         nus = list(set(nums))#得到一个无序的无重复数字的list
4         nus = sorted(nus)
5         for i in range(len(nus)):
6             nums[i] = nus[i]
7         return len(nums[:len(nus)])

 

posted @ 2020-07-01 09:58  你的雷哥  阅读(196)  评论(0编辑  收藏  举报