Loading

LeetCode 026 Remove Duplicates from Sorted Array

题目描述:Remove Duplicates from Sorted Array

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].

 Java:

    public int removeDuplicates(int[] nums) {
        
        if (nums.length < 2) {
            return nums.length;
        }

        int i = 1;
        int j = 0;

        while (i < nums.length) {
            if (nums[i] == nums[j]) {
                i++;
            } else {
                j++;
                nums[j] = nums[i];
                i++;
            }
        }

        return j + 1;
    }

 

posted @ 2015-02-07 16:27  Yano_nankai  阅读(113)  评论(0编辑  收藏  举报