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-27. Remove Element #43

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

LeetCode-27. Remove Element #43

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

Comments

@ninehills
Copy link
Owner

ninehills commented Aug 4, 2017

问题

https://leetcode.com/problems/remove-element/description/

Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example:
Given input array nums = [3,2,2,3], val = 3

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

思路

思路和 #42 比较相似,也是采用双指针的方法,一个指针去遍历nums,另外一个指针原地更新array

解答

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

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

#4 20170804

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