Leetcode - Remove Duplicates from Sorted Array

Question

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.

Java Code

public int removeDuplicates(int[] nums) {
    final int n = nums.length;
    if(n == 0) return 0;
    if(n == 1) return 1;

    int i = 0;//指针i指向当前不重复子数组末位的下一位
    int j = 1;//指针j用于遍历数组元素

    //遍历数组起始的无重复元素区间
    while(nums[i++] != nums[j++]) {
        if(j == n) return n;
    }

    while(j < n) {
        if(j == n-1) {//如果已遍历到数组末尾,则判断最后两个元素是否相同
            if(nums[i] != nums[j]) {
                nums[i] = nums[j];
                return i+1;
            }
            else
                return i;
        }

        if(nums[i] != nums[j]) {//两个元素值不相等则用j指针对应的值覆盖i指针对应的值
            while(nums[j] == nums[j + 1]) {//与nums[j]相等的元素可能有多个,找到最后一个
                if(j == n-2) {
                    nums[i] = nums[j];
                    return i+1;
                }
                j++;
            }
            nums[i++] = nums[j++];
        }else//两个元素值相等则使j指针一直跳过重复的元素
            j++;
    }

    return i;
}

说明

  • 本题算是另一题的加强版,基本解题思路差不多,但不同的是,本题的重复元素可能不止一个数值,所以需要仔细分析两个指针之间的关系,还有需要注意的一点就是不要让指针j越界

更新

2016.04.27

public int removeDuplicates2(int[] nums) {
    int n = nums.length;
    if(n == 0) return 0;
    int i = 0;//用于指向当前无重复元素子数组的下一位
    int j = 0;//用于遍历nums数组的元素

    //遍历数组起始的无重复元素区间
    while(nums[i++] != nums[j++]) {
        if(i == n) return n;
    }

    while(j < nums.length) {
        if(nums[j] == nums[j - 1])//如果相邻元素的值相等,则继续遍历
            j++;
        else//否则,用j指针对应的值覆盖i指针对应的值,再继续遍历
            nums[i++] = nums[j++];
    }

    //返回无重复元素子数组的最大长度
    return i;
}

你可能感兴趣的:(LeetCode,remove,Duplicates)