Leetcode.26 delete duplicates in sorted array

Title Description

Given a sorted array, you need to remove the recurring elements in place, so that each element appears only once, after returning the new length of the array is removed.

Do not use extra array of space, you have to modify the input array place and completed under the conditions of use O (1) extra space.

Example 1:

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

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

You do not need to consider beyond the elements of the new array length behind.

Example 2:

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

New function should return the length 5 and the first five elements of the original array nums is modified to 0, 1, 2, 3, 4.

You do not need to consider beyond the elements of the new array length behind.

Description:

Why return value is an integer, but the answer is an array of output it?

Please note that the input array is passed by "reference" mode, which means to modify the input array is visible to the caller within the function.

You can imagine the internal operation is as follows:

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

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

answer

Finger-bis (java)

Ideas:

public int removeDuplicates(int[] nums) {
    if (nums.length == 0) return 0;
    int i = 0;
    for (int j = 1; j < nums.length; j++) {
        if (nums[j] != nums[i]) {
            i++;
            nums[i] = nums[j];
        }
    }
    return i + 1;
    }

Complexity Analysis

  • Time complexity: O (n)
  • Space complexity: O (1)
Published 43 original articles · won praise 20 · views 1459

Guess you like

Origin blog.csdn.net/Chen_2018k/article/details/104463077