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
문제
문제를 간략히 요약하자면 int형 배열 nums안에 포함된 모든 val을 제거하는 것 입니다. 파이썬으로 구현하기에 매우 간단한 것처럼 보이지만 in-place 조건이 붙었기 때문에 val의 제거가 nums 제자리에서 이루어져야 합니다. nums에 포함되어 있는 모든 val 제거 후의 nums의 길이를 int 형으로 반환하면 성공입니다.
풀이
처음에 문제를 읽고 생각난 방법은 단순히 val이 nums에서 없어질 때까지 val을 삭제하는 방법입니다. 정말 쉽게 생각해낼 수 있는 방법이고, 예상대로 오류없이 실행되었지만 실행 시간도 최악이고, 메모리 효율도 최악인 것 같습니다..ㅎㅎ
class Solution:
def removeElement(self,nums: List[int], val: int) -> int:
while(val in nums):
nums.remove(val)
return len(nums)
다음엔 앞서 작성된 예시보다 조금 더 개선된 속도의 풀이입니다. nums의 요소들을 하나씩 꺼내어 삭제하려는 값과 같다면 해당 값을 삭제하고 아니라면 배열의 맨 뒤로 위치 시켜 다음 요소를 검사할 수 있도록 합니다. i의 증가마다 요소가 삭제되거나 or 요소가 배열의 맨 뒤로 보내짐 중 하나로 실행되기 때문에 nums[0]만 판단하는 것 처럼 보여도 실질적으로는 모든 배열의 요소를 검사하는 것 입니다. 하지만 여전히 메모리 효율이 좋지 못하여 개선된 방법도 고민해 보아야 할 것 같습니다.
class Solution:
def removeElement(self,nums: List[int], val: int) -> int:
for i in range(len(nums)):
if nums[0] != val:
nums.append(nums[0])
del nums[0]
else:
del nums[0]
return len(nums)
'자료구조,알고리즘' 카테고리의 다른 글
LeetCode-151 Reverse Words in a String 파이썬 풀 (0) | 2023.08.25 |
---|---|
LeetCode-121 Best Time to Buy and Sell Stock 파이썬 문제 풀이 (0) | 2023.08.24 |
LeetCode-189 Rotate Array 파이썬 문제 풀이 (0) | 2023.08.24 |
LeetCode-169 Majority Element 파이썬 풀이 (0) | 2023.08.24 |
LeetCode-80 Remove Duplicates from Sorted Array II 파이썬 풀이 (0) | 2023.08.24 |