第8周-Python-leetcode-hw1

题目

26. Remove Duplicates from Sorted Array

**Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.**

解题思路

给的数组已经排好序,所以只需要比较当前数字与前一个数字是否相同,若相同则删去当前数字,否则index加1

代码

class Solution:
    def removeDuplicates(self, nums):
        i = 1;
        while i < len(nums):
            if nums[i] == nums[i-1]:
                del nums[i]
                continue
            i += 1
        return len(nums)
if __name__ == '__main__':
    s = Solution();
    print(s.removeDuplicates([0,0,1,1,1,2,2,3,3,4]))

猜你喜欢

转载自blog.csdn.net/weixin_38695404/article/details/80085238
今日推荐