您的位置:首页 > 其它

【Leetcode】从排序数组中删除重复元素

2017-04-16 16:10 507 查看
题目:给定一个排序的数组,删除重复的位置,使每个元素只显示一次并返回新的长度

不要为另一个数组分配额外的空间,您必须使用常量内存来进行此操作。

例如,

给定输入数组nums = [1,1,2],

您的函数应返回长度= 2,与前两个元素NUMS是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 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.

Subscribe to see which companies asked this question.


//思路:遍历一遍数组
//用两个指针,当元素重复时,跳过重复的位置,当不重复的时候,把元素放到正确的位置上去
int removeDuplicates(vector<int>& nums)
{
int temp = nums[0];
int size = 0;
for (int i = 0; i < nums.size();)
{
while (temp == nums[i])
{
i++;
}
if (size == 0)//为什么不直接从1开始,因为有可能元素个数为0,很可能造成数组越界,但是放在循环里面又需要每次进行判断,那有没有更优的解法呢?
{
size++;
}
if (size != i)
{
nums[size++] = nums[i++];
}

}
return size;

}


几种更优的解法:

<一>

int removeDuplicates(vector<int>& nums) {
int i = 0;
for (int n : nums)
if (!i || n > nums[i-1])
nums[i++] = n;
return i;
}


<二>

And to not need the !i check in the loop:

int removeDuplicates(vector<int>& nums) {
int i = !nums.empty();
for (int n : nums)
if (n > nums[i-1])
nums[i++] = n;
return i;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐