Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode-26. Remove Duplicates from Sorted Array #42

Closed
ninehills opened this issue Aug 1, 2017 · 1 comment
Closed

LeetCode-26. Remove Duplicates from Sorted Array #42

ninehills opened this issue Aug 1, 2017 · 1 comment
Labels

Comments

@ninehills
Copy link
Owner

ninehills commented Aug 1, 2017

问题

https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
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.

思路

刚开始以为就是算出去除重复后的长度,但是报wrong answer,看评论才知道要求同时修改list,思路为双指针法

解答

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        i = 0
        for j in range(1, len(nums)):
            if nums[j] != nums[i]:
                i += 1
                nums[i] = nums[j]
        return i+1

a = [1,1,2,2,3,4]
print Solution().removeDuplicates(a)
print a
@ninehills
Copy link
Owner Author

#4 20170803

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant