코딩테스트/알고리즘
LeetCode 리트코드 ) Remove Element (Python)
디깅
2022. 7. 27. 11:27
728x90
https://leetcode.com/explore/learn/card/array-and-string/205/array-two-pointer-technique/1151/
Explore - LeetCode
LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.
leetcode.com
문제
풀이
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
latnum = 0
for i in range(0,len(nums)):
if(nums[i] != val):
nums[latnum] = nums[i]
latnum += 1
return latnum
같은 경우에 pop으로 빼면서 했더니 nums의 길이가 변경되어서 IndexError: list index out of range 가 발생.
같지 않은 경우에만 그 값의 개수를 출력하면 되므로,
같지 않은 값을 리스트의 앞쪽으로 옮기고, 옮긴 숫자만큼 갯수를 체크해서 return한다.
반응형