【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
从排序数组中删除重复数组IIFollow 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; }
相关文章推荐
- LeetCode 分类练习(1)—— 在数组中移动指定元素、删除指定元素、删除重复元素
- leetcode_26. Remove Duplicates from Sorted Array 在排好序的数组中删除重复的数字,不允许分配其他空间
- 寻找数组中和为指定数字的子数组,可以重复,Leetcode 39
- [每日练习]Amazon面试题:数组有N-2个数字,数字的范围为1 ... N,没有重复的元素,要求打印缺少的2个数字,不可以用额外的空间
- 问题描述如下: 有2.5亿个整数(这2.5亿个整数存储在一个数组里面,至于数组是放在外存还是内存,没有进一步具体说明); 要求找出这2.5亿个数字里面,不重复的数字的个数; 另外,可用的内存限定为600M; 要求算法尽量高效,最优;
- LeetCode: Remove Duplicates from Sorted Array II(在排序数组中删除重复元素)
- java 两个int数组删除重复的数字,并返回删除后的数组
- 数组有N+M个数字, 数字的范围为1 ... N, 打印重复的元素, 要求O(M + N), 不可以用额外的空间
- 删除排序数组中的重复数字
- JS删除数组指定对象或者指定下标 删除数组重复值
- LeetCode(Remove Duplicates from Sorted List) 两道删除排序链表中重复数字
- 给数组添加一个根据指定下标删除元素的方法、得到0-100的随机数不重复(js)、得到外联样式的css样式值
- randnumber_mn.c 生成一个数组,包括k个不重复的整数,并且要求这些整数范围为[m,n),生成的结果中不能包含inum中的数字,size表示inum的长度
- 计蒜客-第22题:排序后的数组删除重复数字
- c语言排序后删除数组中重复的数字再排序输出
- [每日练习]数组有N+M个数字, 数字的范围为1 ... N, 打印重复的元素, 要求O(M + N), 不可以用额外的空间
- leetcode:Remove Duplicates from Sorted Array(去掉数组重复数字,常数空间限制)【面试算法题】
- JS删除数组指定对象或者指定下标 删除数组重复值
- 计蒜客 22题 排序后的数组删除重复数字
- leetcode-1 Two Sum 找到数组中两数字和为指定和