去掉有序数组中重复数字 原地 leetcode java (最简单的方法)
2014-07-09 20:21
681 查看
1.利用荷兰国旗的思路,每次记住最后一个位置,遇到一个不重复的数,放在它后面,代码很简单。
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 =
Your function should return length =
View Code
2.只要跟end的前一个比较就行了,思路跟上边,就一点不一样,原创啊
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A =
Your function should return length =
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].
public class Solution { public int removeDuplicates(int[] A) { int len=A.length; if(len==0) return 0; int pos=0; for(int i=1;i<len;i++) { if(A[i]!=A[pos]) { pos++; A[pos]=A[i]; } } return pos+1; } }
View Code
2.只要跟end的前一个比较就行了,思路跟上边,就一点不一样,原创啊
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A =
[1,1,1,2,2,3],
Your function should return length =
5, and A is now
[1,1,2,2,3].
public class Solution { public int removeDuplicates(int[] A) { int len=A.length; if(len==0) return 0; if(len==1) return 1; int end=1; for(int i=2;i<len;i++) { if(A[i]!=A[end-1]) { end++; A[end]=A[i]; } } return end+1; } }
相关文章推荐
- JAVA去掉一个已排序数组的重复数字
- java__排序后的数组删除重复数字。给定升序排序的数组,如果数组有 22 个或 22 个以上相同的数字,去掉他们,直到剩下 22 个为止。
- 数据存储——Java数组,去掉重复值、增加、删除数组元素的实现方法
- LeetCode-Remove Duplicates from Sorted Array-从有序数组移除重复-简单逻辑
- leetcode:Remove Duplicates from Sorted Array II (允许重复一次,去掉数组多余数字)【面试算法题】
- LeetCode 80. Remove Duplicates from Sorted Array II(有序数组移除重复数字Ⅱ)
- java常用算法之返回目标数字在有序数组中的位置(假设有序数组中不存在重复数字)
- Java数组去掉重复的方法集
- LeetCode 26 Remove Duplicates from Sorted Array (移除有序数组中重复数字)
- Java数组,去掉重复值、增加、删除数组元素的方法
- javascript和java数组中去掉重复元素的方法
- Java数组,去掉重复值、增加、删除数组元素的实现方法
- Java数组去掉重复的方法集
- leetcode:Remove Duplicates from Sorted Array(去掉数组重复数字,常数空间限制)【面试算法题】
- Java简单易懂的生成不重复随机整数数组的方法
- Java中从[1,36]随机生成7个不重复的数字,放入一个数组中
- java去掉数组中重复的数据和遍历数据
- js去掉数组重复的扩展方法
- java数组简单介绍以及其方法
- 简单的从5个数字里面取4个不重复的数字-java版