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

本文介绍了一个高效的数组去重算法,该算法能在常数空间复杂度下移除有序数组中的重复元素,只保留每个元素的第一个实例,并返回去重后的数组长度。通过使用两个指针,一个用于遍历数组,另一个用于存储新数组的当前位置,该算法实现了原地修改数组的目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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

参考文献:LiveToolkit

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值