題目: Remove Duplicates from Sorted Array

難度:easy

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

說明:

Given a sorted array nums, remove the duplicates in-place such that each element appear only onceand return the new length.

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,1,2,2,2,3,4,5,6,6,7,7,8]

1,2,6,7皆有重複,所以把多的挑掉,只留一個

答案是:[1,2,3,4,5,6,7,8]

 

解題方法:

其實很簡單,我們只要把陣列放入set中即可

因為set會把重複的值去除掉

 

程式碼:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        set <int> myset;
        for(int i=0;i<nums.size();i++)
           {
            myset.insert(nums[i]);
           }
            nums.clear();
          for (auto it=myset.cbegin(); it != myset.cend(); ++it)
             {
             nums.push_back(*it);
          }
        return nums.size();
    }
};

 

arrow
arrow

    kyo 發表在 痞客邦 留言(0) 人氣()