//GitHub https://github.com/vellimole0621
LeetCode - Remove Element
문제 설명
:
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
- Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
- Return k.
=> 수로 이루어진 배열 nums와 특정 수 val이 주어진다. nums의 배열의 요소 중 val 값과 같은 경우 그 요소를 삭제하고. 최종 nums의 크기를 return 해라.
내 풀이
:
인덱스 제어를 위해 removal 변수 선언 > nums 배열 길이 만큼 반복문 생성 > i 인덱스에서 removal 빼서 인덱스 제어 > if i가 nums 배열 길이와 같은 경우 반복문 종료 / if nums[i] == val 인 경우, 그 요소를 삭제하고 removal 변수 값 1 증가 > 최종적으로 nums의 크기를 return
# Remove Element
# https://leetcode.com/explore/learn/card/fun-with-arrays/526/deleting-items-from-an-array/3247/
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
removal = 0
for i in range(0, len(nums)):
i = i - removal
if i == len(nums):
break
if nums[i] == val:
del nums[i]
removal += 1
return len(nums)
'프로그래밍 > Python' 카테고리의 다른 글
[파이썬 Python/알고리즘] LeetCode - Replace Elements with Greatest Element on Right Side (0) | 2023.09.17 |
---|---|
[파이썬 Python/알고리즘] LeetCode - Check If N and Its Double Exist (0) | 2023.09.11 |
[파이썬 Python/알고리즘] LeetCode - Merge Sorted Array (0) | 2023.09.05 |
[파이썬 Python/알고리즘] LeetCode - Duplicate Zeros (0) | 2023.09.05 |
[파이썬 Python/알고리즘] LeetCode - Squares of a Sorted Array (0) | 2023.09.05 |