ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [LeetCode] 26. Remove Duplicates from Sorted Array c++
    Coding Test/LeetCode 2022. 9. 15. 10:28
    728x90

    문제 설명

    Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

    Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

    Return k after placing the final result in the first k slots of nums.

    Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

    제한 사항

    • 1 <= nums.length <= 3 * 104
    • -100 <= nums[i] <= 100
    • nums is sorted in non-decreasing order.

    입출력 예

    Input: nums = [1,1,2]
    Output: 2, nums = [1,2,_]
    Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
    It does not matter what you leave beyond the returned k (hence they are underscores).

    풀이

    nums 배열은 항상 오름차순으로 주어진다.

    nums배열의 중복된 값은 삭제시키고 nums벡터의 크기를 반환시키는 문제이다.

    나는 set 을 사용해서 중복된 값 없이 저장되도록 했다.

    그리고 nums배열도 변경시켜야 한다.

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            set<int> nSet;
            
            for(const auto &it : nums){
                nSet.insert(it);
            }
            
            nums.assign(nSet.begin(), nSet.end());
            
            return int(nSet.size());
        }
    };

    tow pointer로 푸는 방법이다.

    i, j 번째를 비교하고, 다르다면 서로 위치를 바꿔준다.

    int removeDuplicates(vector<int>& nums)
        {
            int j =0;
            for(int i=1; i<nums.size(); i++)
            {
                if(nums[j] != nums[i])
                {
                    j++;
                    swap(nums[i],nums[j]);
                }
            }
            return (j+1);
        }
    728x90

    댓글

© 2022. code-space ALL RIGHTS RESERVED.