LeetCode (Elementary Algorithm) Arrays --- remove duplicates from a sorted array

topic

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:

给定数组 nums = [1,1,2], 

函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 

你不需要考虑数组中超出新长度后面的元素。

Example 2:

给定 nums = [0,0,1,1,1,2,2,3,3,4],

函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。

你不需要考虑数组中超出新长度后面的元素。

illustrate:

Why is the returned value an integer, but the output answer is an array?

Note that the input array is passed "by reference" , which means that modifications to the input array within the function are visible to the caller.

You can imagine the internal operation as follows:

// nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝
int len = removeDuplicates(nums);

// 在函数里修改输入数组对于调用者是可见的。
// 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

Parse

When encountering repetition, the first reaction in our minds is to have the data structure characteristic of Hash—uniqueness, but this question requires you to modify the input array in place and use O(1) extra space to complete it, so that A lazy way to use HashSet can pass.

1) Ideal situation

Use two pointers, one in the high position and one in the low position, L does not move when they are equal, and H jumps to the next

1 1 1 2 2 2 3 3 4 4

L H

At different times, give the value of H to the next position of L

1 2 1 2 2 2 3 3 4 4

L H

and so on

1 2 3 2 2 2 3 3 4 4

​ L H

At the end, the length is the index of L + 1

1 2 3 4 2 2 3 3 4 4

​ H H

2) Special circumstances

Even if there is only one 1, it doesn't matter because the assignment is done at the next position of L

1 2 2 2 3 3 4 4

L H

Code

class Solution {
    public int removeDuplicates(int[] nums) {
            int l=0,h=1; //l---低位    h---高位
            while(h<nums.length) {
                if(nums[h]!=nums[l])
                {   
                    l++;
                    nums[l]=nums[h];
                }
                h++;
            }
            return l+1;
        }
}

Guess you like

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