移除有序數組的重複數字(Remove Duplicates from Sorted Array)

題目

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 A = [1, 1, 2], Your function should return length = 2, and A is now [1, 2] 

題目大概意思是說給你要一個有序的數組,把裏面的重複的部分刪掉使得這個數組的每個元素就出現一次,然後返回移除後的數組長度。要求:不同使用額外的數組空間,只能在這個數組裏面完成。

分析

題目比較簡單,已知數組有序,只保留一個,其實就是去重處理。可以使用雙重指針來做:新數組指針和舊數組指針,舊數組指針用於遍歷整個數組,新數組指針從用於存儲新的去重後的數據。

代碼

/**************************************
* 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 A = [1, 1, 2],
* Your function should return length = 2, and A is now [1, 2]
**************************************/
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
  /* Time: O(n), Space: O(1) */
	int removeDuplicates(vector<int> &nums) {
		if (nums.empty()) {
			return 0;
		}
		
		int start = 0;
		for (int i = 1; i < nums.size(); i++) {
			if (nums[start] != nums[i]) {
				start++;
				nums[start] = nums[i];
			}
		}
		
		for (int i = nums.size() - 1; i > start; i--) {
			nums.pop_back();
		}
		
		return start + 1;
	}
};

int main(void) {
	Solution* s = new Solution();
	vector<int> nums;
	nums.push_back(1);
	nums.push_back(1);
	nums.push_back(2);
	nums.push_back(2);
	nums.push_back(2);
	nums.push_back(3);
	
	cout << "Solution 1: " << s->removeDuplicates(nums) << endl;
	
	for (int i = 0; i < nums.size(); i++) {
		cout << nums[i] << ";";
	}
	
	delete s;
	return 0;
}

 

發佈了84 篇原創文章 · 獲贊 19 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章