Leetcode NO.26 Remove Duplicates from Sorted Array
来源:互联网 发布:excel数据比对怎么做 编辑:程序博客网 时间:2024/05/22 07:46
本题题目要求如下:
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 A = [1,1,2]
,
Your function should return length = 2
, and A is now [1,2]
.
我的解法相对比较费时间,是O(nlogn)的时间复杂度,是把重复元素都置为INT_MAX然后最后sort一遍。
不过看到了可以用two pointer解决之后,问题就比较简单了,可以得到O(n)的最优解:
解法就是一个pointer用来遍历数组,另外一个pointer用来指向最后需要得到的数组的元素,直接上代码了,这题怎么讲都不如直接看代码直接:
class Solution {public: int removeDuplicates(int A[], int n) { if (n == 0) return 0; int i = 0; int j = 1; while (j < n) { if (A[i] == A[j]) ++j; else A[++i] = A[j++]; } return i+1; }};
看来刷题还是有用的,现在再看我第一次的O(nlogn)的想法,简直惨不忍睹,现在上传下最新的code吧,跟上面的基本一样,只不过Leetcode的function的argument改了一下。。
class Solution {public: int removeDuplicates(vector<int>& nums) { if (nums.size() == 0) { return 0; } int cnt = 1; int tmp = nums[0]; for (int i = 1; i < nums.size(); ++i) { if (nums[i] != tmp) { tmp = nums[i]; nums[cnt++] = nums[i]; } } return cnt; }};
再上传一个更为简洁的版本:
class Solution {public: int removeDuplicates(vector<int>& nums) { int id = 1; for (int i = 1; i < nums.size(); ++i) { if (nums[i] != nums[i-1]) { nums[id++] = nums[i]; } } return min(static_cast<int>(nums.size()), id); }};
0 0
- Leetcode NO.26 Remove Duplicates from Sorted Array
- LeetCode--No.26--Remove Duplicates from Sorted Array
- LeetCode(26)Remove Duplicates From Sorted Array
- [leetcode 26] Remove Duplicates from Sorted Array
- [Leetcode] 26 - Remove Duplicates from Sorted Array
- leetcode|26|Remove Duplicates from Sorted Array
- leetcode-26 Remove Duplicates from Sorted Array
- leetcode 26 Remove Duplicates from Sorted Array
- LeetCode 26 Remove Duplicates from Sorted Array
- LeetCode 26 Remove Duplicates from Sorted Array
- LeetCode 26 Remove Duplicates from Sorted Array
- leetcode 26 Remove Duplicates from Sorted Array
- LeetCode---(26) Remove Duplicates from Sorted Array
- Leetcode 26 Remove Duplicates from Sorted Array
- LeetCode 26 - Remove Duplicates from Sorted Array
- Leetcode[26]-Remove Duplicates from Sorted Array
- leetcode 26 -- Remove Duplicates from Sorted Array
- LeetCode 26: Remove Duplicates from Sorted Array
- mysql数据库的使用
- Unity3d 着色器语法(Shader)
- Gentoo更新排除软件包
- 从问题里学习linux命令
- git-flow
- Leetcode NO.26 Remove Duplicates from Sorted Array
- setting up the centos7
- 深入理解JavaScript系列(24):JavaScript与DOM(下)
- .NET Framework中已使用的设计模式
- 个人总结之位运算和与运算
- From Craft to Engineering
- SVN “不能打开文件“.svn/lock” 权限不够”精解
- 表、视图、索引的创建、修改、删除操作等
- 深入理解JavaScript系列(25):设计模式之单例模式