넘치게 채우기

[LeetCode] 26. Remove Duplicates from Sorted Array 본문

PS/LeetCode

[LeetCode] 26. Remove Duplicates from Sorted Array

riveroverflow 2023. 7. 2. 13:12
728x90
반응형

https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/?envType=study-plan-v2&envId=top-interview-150 

 

Remove Duplicates from Sorted Array - LeetCode

Can you solve this real interview question? Remove Duplicates from Sorted Array - Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place [https://en.wikipedia.org/wiki/In-place_algorithm] such that each unique element ap

leetcode.com

문제 유형 : 배열

문제 난이도 : Easy

 

문제

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. Then return the number of unique elements in nums.

Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
  • Return k.

배열의 중복값을 없애되, 요소들의 순서 규칙을 유지하시오. 중복값을 없애고 난 뒤의 요소의 개수를 반환하시오.

 

풀이

문제 그대로 작성해주면 된다. erase와 unique를 이용하여 중복된 요소들을 없애주고, 배열의 크기를 반환하면 된다.

 

코드(C++)

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        nums.erase(unique(nums.begin(), nums.end()), nums.end());
        return nums.size();
    }
};
 
728x90
반응형

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

[LeetCode] 137. Single Number II  (0) 2023.07.04
[LeetCode] 80. Remove Duplicates from Sorted Array II  (0) 2023.07.03
[LeetCode] 27. Remove Element  (0) 2023.07.01
[LeetCode] 88. Merge Sorted Array  (0) 2023.06.30
[LeetCode] 20. Valid Parentheses  (0) 2023.06.29