Leetcode 26. Remove Duplicates from Sorted Array

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 26. Remove Duplicates from Sorted Array相关的知识,希望对你有一定的参考价值。

Given a sorted array, 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 in place with constant memory.

For example,
Given input array 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 new length.

本题要求在 sroted list 中 in-place 的进行去重操作,并返回去重后的长度。

思路: 假设经过一些步骤之后,nums的前段已经是去重完毕的序列了。设 ind 为去重序列之后的第一个index。从ind往后找,如果nums[i] != prev,那么 nums[ind] = nums[i], 然后去重完毕的子序列边长了一格,所以ind += 1。这个prev 由于总是位于ind的前一个,所以不单独定义用nums[ind-1]也可以。

1, 2,3, 4,  4, 5, 6, 7, 7, ...

          prev, ind

 1 class Solution(object):
 2     def removeDuplicates(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         n = len(nums)
 8         if n <= 1:
 9             return n
10         
11         ind = 1
12         for i in range(1,n):
13             if nums[i] != nums[ind-1]:
14                 nums[ind] = nums[i]
15                 ind += 1
16         return ind

 


以上是关于Leetcode 26. Remove Duplicates from Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]26. Remove Duplicates from Sorted Array

Leetcode 26. Remove Duplicates from Sorted Array

[leetcode-26-Remove Duplicates from Sorted Array]

Leetcode----26. Remove Duplicates from Sorted Array

LeetCode26. Remove Duplicates from Sorted Array

LeetCode 26. Remove Duplicates from Sorted Array