[LeetCode] Remove Duplicates from Sorted Array

前言

Remove Duplicates from Sorted Array是比較平易近人的一道題,做的時候直接模擬AC,後來在網上看到有STL做法,利用現成的函數和工具就是簡便啊。


題目

題目鏈接

描述如下:

Given a sorted array,remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

大意就是已經排序好了的數組,不開新空間,把重複元素移除並返回處理後的新長度。要注意的是“It doesn't matter what you leave beyond the new length.”

思路

簡單分析一下,思路就是一個循環再加一個索引,當檢測到兩元素不等,就寫入。具體見代碼。

代碼

Solution 1:遍歷移動

class Solution {
public:

    int removeDuplicates(vector<int>& nums) {
        if(nums.size()==0)
            return 0;
        else
        {
            int index = 0;
            int len = nums.size();
            for(int i = 0;i<len;i++)
            {
                if(nums[index] != nums[i])
                {
                    nums[++index] = nums[i];//當兩個元素不等,向前挪動
                }
            }
            int ans = index + 1;
            return ans;//即去重後的數組長度
        }
    }
};

Solution 2:使用STL

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        return distance(nums.begin(),unique(nums.begin(),nums.end())); 
    }
};

補充

關於Unique()的說明,可參考這篇博文

此題能夠使用Unique的一大原因是這是一個已排序數組,換句話說,如果有重複的多個元素,它們勢必是相鄰的。這就爲使用unique提供了保證。







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章