본문 바로가기
Problem Solving

[C++] [LeetCode 26] Remove Duplicates from Sorted Array

by tls1107 2021. 8. 9.
728x90
반응형


문제 풀기 전 생각 : 

/*
반복문으로 바로 전 원소와 비교하며
만약 바로 전 원소가 현재 원소보다 크다면 count를 리턴하고
그렇지 않다면 전 원소를 현재 원소로 채우고
count를 증가시킨다.
*/

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size() == 0) return 0;
        int x = nums[0];
        int count = 1;
        for(int i=1 ; i<nums.size() ; i++){
            if(nums[i] == x) continue;
            else if(nums[i] < x){
                return count;
            }
            else {
                nums[count++] = nums[i];
                x = nums[i];
                
            }
        }
        return count;
    }
};

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


풀 때 어려웠던 점 또는 느낀점 :

Custom judge 제대로 살펴보지 않아

몇번 틀렸다...

다음부턴 제대로 살펴봐야지


개선방안 :

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int i,j,n=nums.size();
        if(n==0) return 0;
        i=0;
        for(j=1;j<n;j++){
            if(nums[i]!=nums[j]){
                nums[++i]=nums[j];
            }
        }
        return i+1;
    }
};

비슷한 접근접이지만 조금 더

간결해진거 같다.

참고해야겠다 

728x90
반응형

댓글