cKK

............当你觉得自己很辛苦,说明你正在走上坡路.............坚持做自己懒得做但是正确的事情,你就能得到别人想得到却得不到的东西............

导航

26. Remove Duplicates from Sorted Array

Posted on 2016-01-26 23:36  cKK  阅读(98)  评论(0编辑  收藏  举报

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 class Solution {
    public int removeDuplicates(int[] nums) {
        	int sum = 1;
		for (int i = 1; i < nums.length; i++) {
			if (nums[i] - nums[i - 1] != 0) {
				sum++;
				nums[sum - 1] = nums[i];
			}
		}
		return sum;
    }
}