您的位置:首页 > 其它

【leetcode】删除数组中指定要求的重复的数字

2017-04-16 18:28 591 查看

1. 给定一个数组和一个值,删除该值的所有实例,并返回新长度。 不要为另一个数组分配额外的空间,您必须使用常量内存来进行此操作。

元素的顺序可以改变。

Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example:
Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.


题解:

int removeElement(vector<int>& nums, int val) {
int begin=0;
int end=nums.size();
for(int i=0;i<end;++i)
{
if(nums[i]!=val)
{
nums[begin++]=nums[i];
}
}
return begin;
}


2.Remove Duplicates from Sorted Array II

从排序数组中删除重复数组II

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],

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


思路:已序数组超过2次去重,已序?

总结:两个指针下表=下标,一个用来遍历,一个用来将正确的元素放在正确的位置,

特别注意:

1.边界条件的判断,是否元素个数为0可以通过?

2.重复元素多于2个怎么解决?

3.怎么样不会崩溃?

int removeDuplicates(vector<int>& nums) {

int size=0;
for(int i=0;i<nums.size();++i)
{
if(i<2)
{
size++;
}

else if(nums[i]>nums[size-2])
{
nums[size++]=nums[i];
}

}
return size;
}


再来学习一下更新颖的解法:

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