복's

[ LeetCode - 27 ] Remove Element 본문

알고리즘/LeetCode

[ LeetCode - 27 ] Remove Element

나복이 2023. 11. 1. 14:23
728x90

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

 

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

2023.11.01 오늘의 easy 문제 ~ 

난이도는 easy 였지만 오래 풀어 버렸다는거 ㅎ..

주어진 배열을 그대로 사용 했어야 했다.


[ 📌 풀이 ]

그냥 리스트에 요소를 삭제해주면 되는 문제였다.

리스트의 요소가 주어진 val과 값이 같다면 해당 요소를 삭제 하면 되는 문제로 인덱스를 구해서 del을 이용해도 될거 같기도 하고,

나는 개수를 구해서 그 개수만큼 remove를 사용해서 삭제 했다.


[ 📌 코드 - Python ]

"""
# Author    : Lee In Bok 
# Date      : 2023.11.01(Wed)
# Spend Time: 17m 03s
# Runtime   : 40 ms (Beats 60.28%)
# Memory    : 16.2 MB (Beats 43.55%)
# Algoritm  : List
"""

from typing import List

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        cnt = nums.count(val)

        for _ in range(cnt):
            nums.remove(val)

s = Solution()
result = s.removeElement([3,2,2,3], 3)

print(result)

[ 📌 다른 사람 코드 - Python ]

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        while val in nums:
            nums.remove(val)

[ 📌 시간이 오래 걸리는 코드 - Python ]

from typing import List

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        cnt = nums.count(val)

        for _ in range(cnt):
            nums.remove(val)

[ 📌 결과 ]

[ Result ]

728x90