leecode 解题总结:26 Remove Duplicates from Sorted Array

#include <iostream>
#include <stdio.h>
#include <vector>

using namespace std;
/*
问题:
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 nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

分析:
此题就是删除数组中重复元素,应该可能和查找上下区间的函数有关。
要求不能分配额外空间到另外一个数组,花费常量空间。

问题在于:
如何判断一个元素是否是重复的,也就是需要求出同一个数值的起始下标
由于删除后带来的问题是需要将元素向前移动,所以希望移动的次数尽可能少。
因此如果是从后向前判断重复元素删除并移动的话,每次删除都需要移动;
          从前向后判断重复元素,每次只需要移动一小部分。
所以最终还是从前向后判断重复元素。
设数组为A,记录当前元素为x,下标为index,如果后面一个元素和x相同,直接继续遍历下一个元素;直到遍历一个元素和x不同,
记该元素为y,令x后面一个元素为y,即A[index+1] = y,并更新index++即可。
最后将index到原来数组元素长度length之间的所有元素全部删除

输入:
3(数组元素个数)
1 1 2
10
1 2 2 2 3 3 4 5 5 6
1
1
2
1 1
输出:
2(新数组的长度)
6
1
1

关键:
1 所以最终还是从前向后判断重复元素。
设数组为A,记录当前元素为x,下标为index,如果后面一个元素和x相同,直接继续遍历下一个元素;直到遍历一个元素和x不同,
记该元素为y,令x后面一个元素为y,即A[index+1] = y,并更新index++即可。
最后将index到原来数组元素长度length之间的所有元素全部删除
*/

void print(vector<int>& nums)
{
	if(nums.empty())
	{
		cout << "nums is empty" << endl;
		return ;
	}
	int length = nums.size();
	for(int i = 0 ; i < length ; i++)
	{
		cout << nums.at(i) << " ";
	}
	cout << endl;
}

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.empty())
		{
			return 0;
		}
		int size = nums.size();
		int curValue = nums.at(0);
		int index = 0;
		for(int i = 1 ; i < size ; i++)
		{
			if(nums.at(i) != curValue)
			{
				nums.at(index + 1) = nums.at(i);
				index++;
				curValue = nums.at(i);
			}
		}
		//删除index+1到size之间的所有元素
		nums.erase(nums.begin() + index + 1 , nums.begin() + size);
		int length = nums.size();
		//print(nums);
		return length;
    }
};

void process()
{
	int num;
	vector<int> datas;
	int value;
	while(cin >> num)
	{
		datas.clear();
		for(int i = 0 ; i < num ; i++)
		{
			cin >> value;
			datas.push_back(value);
		}
		Solution solution;
		int result = solution.removeDuplicates(datas);
		cout << result << endl;
	}
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值