5 DERECHA

27. Remove Element 본문

카테고리 없음

27. Remove Element

kay30 2021. 7. 8. 19:10

I use python language as a solving this problem. 

Even though you are not using python, the concept of approach the question will be helpful.

Approach

In this problem, the given an integer array "nums" and variable "val" are our parameter to get from problem.

All we have to do remove the element("val") in the array("nums").

But you have to look through this sentence.

"Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory."

So we should not declare more array. I just declare only two variable.

One of them's name is 'idx' and I will use this name as a index of nums pointing the position to store new integer from the array "nums" (not the element"val").

And another one is just length of nums. I just use this variable for convenience.

So  first of all, I needed to check whether length of nums is less than one.

And if it is not, I will search the array "nums" using for sentence. 

And if nums[i] is not "val", I will store the integer while adding my variable "idx"

You can check this below the code.

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        idx=0
        lena = len(nums)
        if lena == 0:
            return 0
        elif lena == 1:
            if nums[0] == val:
                return 0
            else :
                nums[0] = nums[0]
                return 1
        for i in range(0, len(nums)):
            if nums[i]!=val:
                nums[idx] = nums[i]
                idx +=1
        for i in range(lena-1, idx, -1):
            nums[i] = '0' 
        return idx