LeetCode Remove Duplicates from Sorted Array
来源:互联网 发布:淘宝直播间 编辑:程序博客网 时间:2024/06/12 23:22
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]
.
class Solution {public:int removeDuplicates(int A[], int n) { if (n <= 1) return n; while(j < n) { if (A[i] == A[j]) ++j; else A[++i] = A[j++]; } return i + 1;}};
第二次刷这个题,两次写的代码都不如上面这种精简(By 三姐)。其实算法很简单,都是一样的。
附:
第一次的代码:
class Solution {public: int removeDuplicates(int A[], int n) { if(n == 0) return 0; int i = 0; for(int j = 1; j < n; j++) { if(A[j] != A[i]) { i++; A[i] = A[j]; } } return i + 1; }};
第二次的代码:
class Solution {public: int removeDuplicates(int A[], int n) { int j = 1; int m = min(1,n); for(int i = 0; j < n; i++) { while(A[j] == A[i] && j < n) j++; if(j < n) { A[i+1]=A[j]; m++; j++; } } return m; }};
0 0
- [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
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- leetcode 35: Remove Duplicates from Sorted Array
- [LeetCode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array
- Leetcode: Remove Duplicates from Sorted Array
- [leetcode] Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array
- [LeetCode]Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array
- [leetcode]Remove Duplicates from Sorted Array II
- 程序异常监视脚本
- python抓取搜索到的url,小型爬虫
- servlet及编程规范
- jboss 5 : JMS
- Java 项目中,用到cookie记住我中,存在登录名乱码问题?
- LeetCode Remove Duplicates from Sorted Array
- test
- vsftpd配置详解
- redhat7.0修改开机启动模式
- Vim强大的自动补全YCM
- 【第11篇】通过GSON的TreeReader与JsonReader去处理json数据
- 火星人敏捷开发手册视频培训上线了!
- 如何在Mac上新建txt文件,以及打开txt文稿的乱码问题如何解决
- Java---18---多线程:等待唤醒机制