1. 程式人生 > >LeetCode刷題-26—— Remove Duplicates from Sorted Array(刪除排序陣列中的重複項)

LeetCode刷題-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.

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