移除有序数组的重复数字(Remove Duplicates from Sorted Array)

被刻印的时光 ゝ 提交于 2020-01-27 06:23:55

题目

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;
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!