본문 바로가기

Algorithm/Leetcode

[Top Interview 150 - Array / String] 27. Remove Element

[Q] [Easy]

Given an integer array nums and an integer val, 
remove all occurrences of val in nums in-place. 
The order of the elements may be changed. 
Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val be k, 
to get accepted, you need to do the following things:

Change the array nums such that the first k elements of nums contain the elements 
which are not equal to val. 
The remaining elements of nums are not important as well as the size of nums.

Return k.

 

  • leetcode 에 익숙해지는 중이다. 문제를 이해했는데도 list에 '_' 로 대체하는건 문제가 아니었나보다.
for n in nums:
	if n == val:
    	nums.remove(n)

 

  • 처음에 nums 에서 val 제외 시킬 때 이렇게 하려고 했으나, 잘 안 먹혔다. 그래서 아래와 같이 변경해줌.
# Answer

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        
        i = len(nums)

        # nums - val
        while val in nums:
            nums.remove(val)

        # len(nums)
        k = len(nums)                
                
        # val -> _
        p = i - k
        nums += '_' * p


        return k