2.1.1 从排序数组中删除重复项

给定一个排序的数组,在适当的位置删除重复项,使每个元素只出现一次
并返回新长度。
不要为另一个数组分配额外的空间,您必须使用固定内存就地执行此操作。
例如,给定输入数组A=[1,1,2],
函数应该返回length=2,现在A是[1,2]。

全代码如下:

#include<iostream>
#include<string>
#include<vector>
using namespace std;
constexpr auto SIZE = 100;

void del(int *a, int *lenth, int j);//这里lenth传地址操作
void print(int *a, int lenth);//打印数组操作
int main()
{
	int a[SIZE] = { 0 };
	int i = 0,j=1;
	int lenth = 0;
	while (cin >> a[i])
	{
		i++;
		lenth++;
	}//输入数据到数组
	i = 0;
	print(a, lenth);

	while (j != lenth)//遍历整个数组
	{
		if (a[i] == a[j])
		{
			del(a, &lenth, j);//删除数组j位置上的元素
		}
		else
		{
			++i; 
			++j;
		}
	}
	
	print(a, lenth);
	return 0;
}

void print(int *a, int lenth)
{
	for (int i = 0; i < lenth; ++i)
	{
		cout << a[i] << " ";
	}
	cout << endl;
}

void del(int *a, int *lenth, int j)
{
	for (int i = j; i < *lenth; i++)
	{
		a[i] = a[i+1];
	}
	(*lenth)--;
}

下面放点不同的解法

代码1
// LeetCode, Remove Duplicates from Sorted Array
// 时间复杂度 O(n),空间复杂度 O(1)

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0;
int index = 0;
for (int i = 1; i < nums.size(); i++) {
if (nums[index] != nums[i])
nums[++index] = nums[i];
}
return index + 1;
}
};

代码2

// LeetCode, Remove Duplicates from Sorted Array
// 时间复杂度 O(n)空间复杂度 O(1)

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
return distance(nums.begin(), unique(nums.begin(), nums.end()));
}
};

代码3

// LeetCode, Remove Duplicates from Sorted Array
// 时间复杂度O(n)空间复杂度 O(1)

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
return distance(nums.begin(), removeDuplicates(nums.begin(), nums.end(), nums.begin()));
}
template<typename InIt, typename OutIt>
OutIt removeDuplicates(InIt first, InIt last, OutIt output) {
while (first != last) {
*output++ = *first;
first = upper_bound(first, last, *first);
}
return output;
}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值