LeetCode刷题-26—— Remove Duplicates from Sorted Array(删除排序数组中的重复项)

链接:

https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/

题目:

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.

Example:

Example 1:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

Notes:

解析:

  • 题目中要求不能重新定义一个新数组,直接在数组上修改
  • 可以定义一个指针new_tail指向第一个数,循环整个数组,如果与指针指向的数不同,就将数赋值给指针指的下一个数,这样就将所有不重复的数全部排在数组前面,然后返回这些不重复的数的长度就是所求值

解答:

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0

        newtail = 0
        for i in range(len(nums)):
            if nums[i] != nums[newtail]:
                newtail += 1
                nums[newtail] = nums[i]

        return newtail + 1

猜你喜欢

转载自blog.csdn.net/u014135752/article/details/80671955