本文主要是介绍【LeetCode】Remove Duplicates from Sorted Array I II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
I、每个数据只允许出现1次
Remove Duplicates from Sorted Array
Total Accepted: 7116 Total Submissions: 21546 My Submissions
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].
II、每个数据最多允许出现2次
Remove Duplicates from Sorted Array II
Total Accepted: 4799 Total Submissions: 16270 My Submissions
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].
因为不能使用多余的空间,所以需要扫描一遍完成。
如果空间多一点的话,这两道题完全没有什么压力,很简单,直接暴力搜索,赋值即可。
说一说基本思路。
因为是有序数组,所以在最开始声明int start = 0。
然后扫描一遍数组,判断当前数据和start是否相等。
对于I,只需要判断当前值和A[start]是否相等,如果不相等,
start++;
A[start] = A[i],
这样就完成了一次判断操作
否则的话继续循环,扫描下一个值。
对于II,需要判断当前值出现的次数。
如果A[start] != A[i],出现的次数应该是1,那么
和I一样
start++;
A[start] = A[i],
否则的话,需要判断,当前数字出现的次数是否大于等于2,如果>=2,那么继续循环扫描下一个数字,
如果<2,直接赋值即可。
I、Java AC
public class Solution {public int removeDuplicates(int[] A) {if(A == null || A.length == 0){return 0;}int len = A.length;int start = 0;for(int i = 1; i < len; i++){if(A[i] != A[start]){start++;A[start] = A[i];}}return start+1;}
}
II、Java AC
public class Solution {public int removeDuplicates(int[] A) {if(A == null || A.length == 0){return 0;}int start = 0;int len = A.length;int twice = 1;for(int i = 1; i < len; i++){if(A[i] != A[start]){twice = 1;start++;A[start] = A[i];}else{twice++;if(twice <= 2){start++;A[start] = A[i];}}}return start+1;}
}
这篇关于【LeetCode】Remove Duplicates from Sorted Array I II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!