LeetCode 문제 풀이

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

로밍맨 2023. 11. 27. 08:00
728x90
반응형

문제 링크

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

 

Remove Element - LeetCode

Can you solve this real interview question? Remove Element - Given an integer array nums and an integer val, remove all occurrences of val in nums in-place [https://en.wikipedia.org/wiki/In-place_algorithm]. The order of the elements may be changed. Then r

leetcode.com

 

element 간의 순서가 변경되어도 상관 없으니, 순차적으로 방문하면서 지워야 하는 element 라면, 맨 뒤에 있는 element 를 현재 위치에 덮어쓰는 방식으로 구현하였습니다.

 

소스 코드는 다음과 같습니다.

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def removeElement(self, nums: List[int], val: int-> int:
        sz = len(nums)
        i = 0
        while i < sz:
            if nums[i] == val:
                nums[i] = nums[sz - 1]
                sz -= 1
            else:
                i += 1
        return sz
cs

 

유튜브에서 라이브로 풀이를 했었는데 반응이 썩 좋지 않았어서, 풀이 영상은 어떻게 할지 아직 고민 중입니다.

 

저작권 라이선스: CC BY (출처만 표시하면 자유롭게 이용 가능)

728x90
반응형