LintCode 521. Remove Duplicate Numbers in Array

題目:
Given an array of integers, remove the duplicate numbers in it.

You should:

  1. Do it in place in the array.
  2. Move the unique numbers to the front of the array.
  3. Return the total number of the unique numbers.

Notice
You don't need to keep the original order of the integers.

思路:

這題使用兩個指針,第一個指針遍歷,第二個指針指向重複的數。

代碼:

class Solution {
public:
    /*
     * @param nums: an array of integers
     * @return: the number of unique integers
     */
    int deduplication(vector<int> &nums) {
        // write your code here
        if (nums.size() == 0)
            return 0;
        if (nums.size() == 1)
            return 1;
        
        sort(nums.begin(), nums.end());
        int count = 0;//第一個指針,記錄重複的數
        //第二個指針,遍歷
        for(int i =1; i<nums.size(); i++){
            if(nums[count] != nums[i]){
                count++;
                nums[count] = nums[i];
            }
        }
        
        return count+1;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • 《達爾文所未知的》解說詞 撰寫(Written):阿爾芒·馬裏耶(The Animal Mother) 翻譯(Tr...
    JENTSON阅读 1,471评论 0 1
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,951评论 0 23
  • 刚看到一篇文章《女人的归宿》,和文中所述的一样,再过几年四十,不过我没有文中所说那样去算命,不是信不信,而是没想过...
    微雨清倾阅读 201评论 0 0
  • 可以趁着醉意什么都说 当然你也有权保持沉默 但你落的每滴泪都将作为爱的证供 谁的名字淬炼成你心魔 不堪回忆重负何处...
    何道元阅读 260评论 0 2