본문 바로가기

Programming/Python

[LeetCode] 27. Remove Element 파이썬(Python) 풀이

문제 링크🔗

https://leetcode.com/problems/remove-element/?envType=study-plan-v2&envId=top-interview-150

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제 설명📝 

정수 배열 nums와 정수 val이 주어졌을 때, nums에서 val과 일치하는 모든 요소를 제거하고, val이 아닌 요소의 개수를 반환하는 Python 함수를 작성해야 합니다. 여기서 중요한 점은, val이 아닌 요소들을 nums 배열의 처음부터 시작하여 연속적으로 배치해야 한다는 것입니다. 나머지 요소들은 중요하지 않습니다.

 

알고리즘🧠 

  1. nums 배열을 순회하면서 val과 일치하지 않는 요소를 찾습니다.
  2. 요소를 찾을 때마다, 그 요소를 배열의 k번째 위치에 배치하고 k를 하나 증가시킵니다.
  3. k를 반환하여 val과 일치하지 않는 요소의 개수를 알려줍니다.

코드💻

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