[leetcode] 26. Remove Duplicates from Sorted Array
https://leetcode.com/problems/remove-duplicates-from-sorted-array
in-place 알고리즘을 사용하여, 주어진 리스트 내의 중복값을 없애는 문제이다.
중복을 없앤 숫자값들을 리스트의 가장 앞에 배치하면 된다.
간단하게 두 개의 포인터를 사용하여 구현할 수 있다.
r 포인터는 리스트를 처음부터 끝까지 순회한다.
l 포인터와 r 포인터가 가리키는 값이 서로 다르면, l 포인터 위치를 하나 증가시키고 l 포인터 자리에 r 포인터 값을 넣는다.
l 포인터가 리스트를 벗어날까봐 걱정할 필요는 없다.
r 포인터가 항상 l 포인터보다 크기 때문에, l 포인터의 최댓값은 r 포인터의 값이 된다.
그리고 r 포인터는 리스트의 range 를 넘기지 않는다.
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
l = 0
for r in range(0, len(nums)):
if(nums[l]!=nums[r]):
l+=1
nums[l]=nums[r]
return l+1
< English (feedback by ChatGPT) >
This is the problem to remove the duplicates in the given list using the in-place algorithm.
(This problem requires removing duplicates from a given list using an in-place algorithm.)
The digit values after removing the duplicates should be placed at the front of the list.
(The unique values should be placed at the beginning of the list.)
I simply implemented using two pointers.
(I implemented this simply using two pointers.)
'r pointer' iterates through the list.
(The r pointer iterates through the list.)
If the values at 'l pointer' and 'r pointer' are not matched, increase 'l pointer' by 1 and put 'r pointer' value into 'l pointer' value.
(If the values at the l and r pointers are different, we increment the l pointer by one and assign the value at r to the new l position.)
We don't need to worry if 'l pointer' exceeds the range of the list.
(We don’t need to worry about the l pointer exceeding the list’s range,)
'r pointer' is always bigger than 'l pointer' so the biggest index of 'l pointer' is the same with 'r pointer'
(because the r pointer is always ahead of the l pointer, so the maximum index l can reach is equal to that of r.)
and 'r pointer' never exceed the range of the list.
(Also, the r pointer never goes beyond the list’s range.)