LeetCode OJ:Remove Duplicates from Sorted Array
来源:互联网 发布:2016淘宝做什么产品好 编辑:程序博客网 时间:2024/06/06 07:44
Remove Duplicates from Sorted Array
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]
.
算法思想:
数组循环前移会超时,所以利用一辅助数组B去除不需要的元素,时间复杂度O(n),空间复杂度O(n)
class Solution {public: int removeDuplicates(int A[], int n) { if(n==0)return 0; vector<bool> B(n,false); for(int i=1;i<n;i++) if(A[i]==A[i-1]) B[i]=true; int count=0; for(int i=0;i<n;i++){ if(!B[i])A[count++]=A[i]; } return count; }};
answer2
时间复杂度O(n),,空间复杂度O(1)
class Solution {public: int removeDuplicates(int A[], int n) { if(n==0)return 0; int cnt=0; for(int i=0;i<n;i++) if(A[cnt]!=A[i]) A[++cnt]=A[i]; return cnt+1; }};
时间复杂度O(n),空间复杂度O(1)
class Solution {public: int removeDuplicates(int A[], int n) { return distance(A,unique(A,A+n)); }};
answer4
时间复杂度O(n),空间复杂度O(1)
class Solution {public: int removeDuplicates(int A[], int n) { int *first=A,*last=A+n,*cur=A; while(first!=last){ *cur++=*first; first=upper_bound(first,last,*first); } return cur-A; }};
0 0
- LeetCode OJ:Remove Duplicates from Sorted Array
- [LeetCode OJ]Remove Duplicates from Sorted Array
- Leetcode OJ Remove Duplicates from Sorted Array
- LeetCode OJ : Remove Duplicates from Sorted Array
- LeetCode OJ Remove Duplicates from Sorted Array
- LeetCode OJ - Remove Duplicates from Sorted Array
- LeetCode OJ - Remove Duplicates from Sorted Array & Remove Element
- LeetCode OJ:Remove Duplicates from Sorted Array II
- LeetCode OJ - Remove Duplicates from Sorted Array II
- LeetCode OJ Remove Duplicates from Sorted Array II
- 【LeetCode OJ 026】Remove Duplicates from Sorted Array
- LeetCode OJ 26 Remove Duplicates from Sorted Array
- LeetCode OJ-26-Remove Duplicates from Sorted Array
- [leetcode][array] Remove Duplicates from Sorted Array
- 【Leetcode】【Array】Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array
- poj 1769 Minimizing maximizer(线段树&dp)
- 整理sqlmap用法,大概地整合了一下,乱了点。
- Hdu 1016 Prime Ring Problem
- 小孩发烧怎么办 - 强烈建议查看转载内容的详情,看视频介绍
- 输入正确的密码,依然无法登陆ubuntu系统
- LeetCode OJ:Remove Duplicates from Sorted Array
- I2C基础知识
- java设计模式之单例模式
- nginx重要的数据结构
- Android layout_weight理解
- C#详细讲解委托_事件
- mysql5.6.14 winx64绿色版安装步骤
- Home Automation & Networking Ebook
- [LeetCode]134.Gas Station