題目:
Given an array of integers, remove the duplicate numbers in it.
You should:
- Do it in place in the array.
- Move the unique numbers to the front of the array.
- 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;
}
};