【Leetcode】从排序数组中删除重复元素
来源:互联网 发布:听力测试电脑软件 编辑:程序博客网 时间:2024/06/11 00:14
- 题目:给定一个排序的数组,删除重复的位置,使每个元素只显示一次并返回新的长度。
不要为另一个数组分配额外的空间,您必须使用常量内存来进行此操作。
例如,
给定输入数组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;}
0 0
- 【Leetcode】从排序数组中删除重复元素
- 每天一道LeetCode-----从有序数组中删除重复元素
- LeetCode 从排序好的列表中删除重复元素
- Leetcode-26-从排序数组中删除重复项
- 删除排序数组中重复的元素
- LeetCode: Remove Duplicates from Sorted Array II(在排序数组中删除重复元素)
- leetcode 26. Remove Duplicates from Sorted Array从排序数组中移出重复元素(双指针)
- LintCode(easy)删除排序数组中重复元素
- 删除数组中重复元素
- 删除数组中重复元素
- 从排序的数组中删除重复项
- 删除已排序数组中的重复元素
- 删除排序数组中的重复元素
- LeetCode 26 Remove Duplicates from Sorted Array(从已排序数组中移除重复元素)
- LeetCode 26 Remove Duplicates from Sorted Array(从已排序数组中移除重复元素)
- Leetcode 80. Remove Duplicates from Sorted Array II(从已排序数组中移除重复元素)
- leetCode- 从有序数组删除重复项
- LeetCode 分类练习(1)—— 在数组中移动指定元素、删除指定元素、删除重复元素
- 不要通过Application Object或者其他全局静态变量来存放数据
- 括号配对问题
- centos7关闭防火墙
- Qt资源整理
- 双线性插值算法的详细总结 .
- 【Leetcode】从排序数组中删除重复元素
- LeetCode
- ios 属性
- 文章标题
- NYOJ 242
- POJ 3186 Treats for the Cows (区间DP)
- python在windows上的安装
- 多重背包
- 微信实验九、微信ThinkPHP5.0机器人自动回复及源码下载