您的位置:首页 > 其它

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

2017-02-03 17:12 381 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: