Remove Duplicates from Sorted Array

来源:互联网 发布:武侠台词 知乎 编辑:程序博客网 时间:2024/05/29 20:04

Problem: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 nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2

 respectively. It doesn't matter what you leave beyond the new length.

题目的要求不仅返回长度,同时原数组删除了重复元素。

public static int removeDuplicates(int[] nums) {int len=nums.length,i=0,j=1;if(len<2)return len;while(j<len){if(nums[i]==nums[j])j++;elsenums[++i]=nums[j++];}return i+1;}


What if duplicates are allowed at most twice?

For example,

Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 

1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.

public static int removeDuplicates(int[] nums) {int len=nums.length,i=1,j=2;if(len<=2)return len;while(j<len){if(nums[i]==nums[j]&&nums[i-1]==nums[j])j++;else{i++;nums[i]=nums[j];j++;}}return i+1;}



0 0