leetcode26:删除排序数组中的重复项

思想:
1.判断列表nums的长度是否小于等于1,若是则返回列表nums的长度,反之跳转2
2.定义一个变量i=0,代表不重复元素的下标。定义for循环,j从1依次变化到len(nums)
3.判断nums[i]是否与nums[j]相等。若否,则i加1,nums[j]赋值给nums[i]。跳转3,直到j==len(nums)-1结束
class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) <= 1:
            return len(nums)
        else:
            i = 0
            for j in range(1, len(nums)):
                if nums[i] != nums[j]:
                    i += 1
                    nums[i] = nums[j]
            return i+1

猜你喜欢

转载自blog.csdn.net/weixin_43160613/article/details/82822936