26. Remove Duplicates from Sorted Array

900次阅读
没有评论
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 1:

Given <em>nums</em> = <strong>[1,1,2]</strong>,

Your function should return length = <strong>2</strong>, with the first two elements of <em>nums</em> being <strong>1</strong> and <strong>2</strong> respectively. It doesn't matter what you leave beyond the returned length.

Example 2:

Given <em>nums</em> = <strong>[0,0,1,1,1,2,2,3,3,4]</strong>,

Your function should return length = <strong>5</strong>, with the first five elements of <em>nums</em> being modified to <strong>0</strong>, <strong>1</strong>, <strong>2</strong>, <strong>3</strong>, and <strong>4</strong> respectively. It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// <strong>nums</strong> is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to <strong>nums</strong> in your function would be known by the caller.
// using the length returned by your function, it prints the first <strong>len</strong> elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}
解法
class Solution:
    def removeDuplicates(self, nums: 'List[int]') -> 'int':
        for x in range(len(nums)-1):
            if x>len(nums):
                return len(nums)
            while x+1<=len(nums)-1 and nums[x]==nums[x+1]:
                nums.pop(x+1)
                
admin
版权声明:本站原创文章,由admin2019-02-11发表,共计1173字。
转载提示:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)