美文网首页
LintCode 521. Remove Duplicate N

LintCode 521. Remove Duplicate N

作者: aammyytt | 来源:发表于2018-04-15 14:40 被阅读0次

題目:
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;
    }
};

相关文章

网友评论

      本文标题:LintCode 521. Remove Duplicate N

      本文链接:https://www.haomeiwen.com/subject/ctddkftx.html