DSA

Remove Element - Leetcode27

림코드 2024. 7. 29. 16:26

Leetcode27 (https://leetcode.com/problems/remove-element/)

Remove element

  • Difficulty: Easy
  • Data structure: Array
  • Pattern: Two pointer

 

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

 

이번 문제는 Leetcode26번과 비슷하지만, 중복값이 아닌 주어진 val을 삭제하고 또한 추가적인 배열을 생성하지 말고 in-place로 풀라고 명시되어 있다. 즉 아래와 같은 nums 배열에서 val인 2를 삭제한 배열의 길이 k 를 리턴하면 된다. 

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]

 

 

i 가 nums 배열을 돌면서 val와 값이 같지 않을때만 nums[k] 의 값을 엎어치면 된다. 결국 k의 인덱스값이 곧 val 을 nums에서 제거하고 남은 element의 카운트가 된다.

 

 

 

 

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        k = 0
        for i in range(len(nums)):
            if nums[i] != val:
                nums[k] = nums[i]
                k += 1

        return k