3-13 1,613 views
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.
给定一有序数组,删除所有重复元素,保证每个元素只出现一次,并返回新数组的长度。不能额外申请空间。如给定数组[1,1,2],处理后应返回长度2,数组的前两个元素分别为1,2。其中,剩余元素如何排序没有要求。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class Solution { public int removeDuplicates(int[] nums) { if (nums.length == 1) return 1; int index = 0; for (int i=1;i<nums.length;i++) { if (nums[index] != nums[i]) { index++; nums[index] = nums[i]; } } return index+1; } } |
版权属于: 我爱我家
原文地址: http://magicwt.com/2014/03/13/remove-duplicates-from-sorted-array/
转载时必须以链接形式注明原始出处及本声明。