-
[Leet Code] 27.Remove Element - EasyCS기초/Algorithm, Data Structures 2023. 8. 3. 00:15728x90반응형
Description
Input: nums => list[int], val => int
Remove all elements same with "val" in the given array "nums" and change the array to starts with the elements which are not same with "val". The array must be changed in place.
Return the number of elements same with "val".
The judge will test below two points:
1. The returned value is correct - name this value as "k"
2. Each element from 0 to "k"-1 in the array "nums" isn't same with "val"
How to solve
Since we need to check all elements, the TC can't be faster than O(n). So I choose to check the element one by one from index 0.
There are 2 cases:
- The selected element isn't same with "val" : we can move on to the next element
- The selected element is same with "val": we need to remove the element
There are 2 ways to remove the elements - remove it (The length of the array will be changed) or replace it to another integer. We simply can replace the element to the last element of the array - which we didn't check yet if it's same with "val" or not - since the order of non-"val" values which have to left in the array once the function finished doesn't matter. After that, we need to mark that the last value doesn't need to be checked.
Code
def removeElement(nums: List[int], val: int) -> int: p1, p2 = 0, len(nums)-1 while p1 <= p2: if nums[p1] != val: p1+=1 continue nums[p1] = nums[p2] p2-=1 return p1
TC O(n) / SC O(1)
728x90반응형'CS기초 > Algorithm, Data Structures' 카테고리의 다른 글
[알고리즘] 정렬 알고리즘 : 합병정렬 (Merge sort) (0) 2023.06.27 [자료구조] 자료구조를 알아야하는 이유와 배열(list), 연결리스트(linked list) (0) 2023.04.01 [Leet Code] Two Pointers (투포인터): 876.Middle of the Linked List - Easy (0) 2023.01.02 [알고리즘] 투포인터(Two pointers)와 슬라이딩 윈도우(Sliding window) (0) 2022.11.13 [알고리즘] 선형 검색과 이진 검색 (0) 2022.11.13