1aaef8d4d9c5252eb51abd0cf256997d
(难度Easy)Problem 26: Remove Duplicates from Sorted Array(有序数组去重)

链接

Remove Duplicates from Sorted Array - LeetCode

难度等级

Easy

题干

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

题意

给定一个有序数组,要求给数组去重,并返回数组长度

这里有一个问题,为什么我们要做的是给数组去重,但是返回类型的不是一个数组而是一个int呢?

这是因为方法传入的是一个引用,题目需要我们直接在引用上操作原数据。最后返回的是新数据的长度。

可以参考下面代码理解一下

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

在上面这个例子当中我们传入的是一个nums数组,返回的是这个数组去重之后的数组长度。经过了方法调用之后,nums数组已经完成了去重,我们通过引用直接在原数据上进行修改的,所以就不必再返回一个新的数组了。

样例

# Example 1:

Given 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 returned length.

# Example 2:

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

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

题解

top Created with Sketch.