MakerHyeon

26. Remove Duplicates from Sorted Array 본문

Algorithm/LeetCode

26. Remove Duplicates from Sorted Array

유쾌한고등어 2022. 12. 21. 13:14

https://leetcode.com/problems/remove-duplicates-from-sorted-array

 

Remove Duplicates from Sorted Array - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


SOLUTION CODE

# PYTHON

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        l = 1

        for r in range(1,len(nums)):
            if nums[r-1]!=nums[r]: # 중복수X 라면
                nums[l]=nums[r] # l위치에 해당 수 넣고
                l += 1 # l위치포인터 한칸 이동
        return l

# C++

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int l = 1, r = 1;
        while( r < nums.size()){
            if(nums[r-1]!=nums[r]){
                nums[l++] = nums[r];
            }
            r++;
        }
        return l;
    }

};

● 포인터 이용

l - 중복되지않은 결과 원소가 담길 다음 위치를 가리킴

r - 이전값과 중복되었는지를 체크하기 위하여, 전체 배열을 돌며 검사할 포인터

'Algorithm > LeetCode' 카테고리의 다른 글

1929. Concatenation of Array  (0) 2023.01.01
347. Top K Frequent Elements  (0) 2022.12.22
1. Two Sum  (0) 2022.12.22
242. Valid Anagram  (1) 2022.12.20
217. Contains Duplicate  (0) 2022.12.20
Comments