leetcode-26 remove duplicates in sorted array (RemoveDuplicatesFromSortedArray) - java

Title: Remove duplicates in sorted array

Given a sorted array, you need to remove duplicate elements in place so that each element occurs only once, and return the new length of the removed array.

Instead of using extra array space, you have to modify the input array in- place and do it with O(1) extra space.

Example 1:

Given an array nums = [1,1,2] ,

The function should return a new length of 2 , and the first two elements of the original array nums are modified to 1,2.

You don't need to consider elements in the array beyond the new length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4] ,

The function should return a new length of 5 , and the first five elements of the original array nums are modified to 0,1,2,3,4.

You don't need to consider elements in the array beyond the new length.

public int removeDuplicates(int[] nums) {
    int length = nums.length;
    if (length == 0)
        return 0;
    if (length == 1)
        return 1;
    int m = nums[0];
    int count = 0;
    int i = 1;
    while (i < length) {
        if (nums[i] == m) {
            ++ count;
        } else {
            m = nums[i];
            nums[i - count] = m;
        }
        ++ i;
    }
    return length - count;

}

Here we must judge the situation of nums.length == 0//I made an error when I did not judge, which proves that there is a test case for an empty array

Note the conditions of the title: (1) an ordered array, (2) no need to consider elements in the array beyond the new length

Variable annotation: m //The non-repeating element of the array, that is, the element of the new array, is initialized to nums[0], and the previous non-repeating element is recorded each time

          count //Number of repeated elements in the array, initialized to 0

         i //The loop subscript, initialized to 1, does not need to judge nums[0]

Ideas: (1) Because it is an ordered array, if an element repeats, it must be continuous and unique.

    //For example [1,1,1,2], 1 repeats, it is continuous and unique, and 1 will not appear later

    (2) Ignore the repeated elements and put the non-repeating elements m into 0 - newLength of nums

    //When traversing to repeated elements, count++, continue to traverse;

    // When traversing to non-repeated elements, m = nums[i], as the new m value, the position where m should be is the current position minus the number of repeated elements ( i-count )

    //即nums[i-count]=m;

    //For example [0,0,1,1,1,2,2,3,3,4], m is 0,1,2,3,4 respectively, put them in nums[0,1,2 respectively ,3,4]

    //返回newLength = nums.length - count

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324782483&siteId=291194637