본문 바로가기

알고리즘_개념 및 문제풀이

리트코드/leetcode/배열 중복 제거/remove-duplicates-from-sorted-array

반응형

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 only using O(1) Extra Memory (Array in-place)

int removeDuplicates(vector<int>& nums) {
    int length = 0;
    if(nums.size()==1){
        return 1;
    }
    if(nums.empty()){
        return 0;
    }
    for(int i = 0; i < nums.size() - 1; i++){
        if(nums[i] != nums[i+1]){
            length += 1;
            nums[length] = nums[i+1];
        }
    }
    nums = vector<int>(nums.begin(), nums.begin()+length+1);
    return length+1;
}
반응형