已排序数组去重
给定一个排序的数组,删除重复,使每个元素最多允许重复两次,并返回新的长度。 不开另外的数组,使得原数组前几位(new length)即为去重后结果。
public static void main(String[] args) { String[] a = {"0","1","2","2","4","5"}; if(a.length==0) { System.out.println(0); }else { int count = 1; for(int i = 1;i<a.length;i++) { if(a[i]==a[count-1]) { continue; }else { a[count]=a[i]; count++; } } System.out.println(count); System.out.println(Arrays.toString(a)); } }
网上
public class Solution { public int removeDuplicates(int[] nums) { int k = 0; for(int i = 1; i < nums.length; i++){ if(nums[i] > nums[k]){ nums[++k] = nums[i]; } } return k+1; } }
参考:https://blog.csdn.net/liyinan11/article/details/71036227
posted on 2019-12-09 14:27 sunshineicy 阅读(304) 评论(0) 编辑 收藏 举报