135.Remove Duplicates from Sorted Array(从排序数组中删除重复项)

题目:

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

给定排序的数组nums,就地删除重复项,使每个元素只出现一次并返回新的长度。

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

不要为另一个数组分配额外的空间,必须通过使用O(1)额外内存修改输入数组来实现此目的。

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.
你的函数应返回length = 2,nums的前两个元素分别为1和2。 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.
您的函数应返回length = 5,将nums的前五个元素分别修改为0,1,2,3和4
It doesn't matter what values are set beyond the returned length.
设置超出返回长度的值无关紧要。

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.

请注意,输入数组通过引用传入,这意味着调用者也将知道对输入数组的修改。

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)nums通过引用传入。(即没有复制)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.调用者可以知道函数中对nums的任何修改。
// using the length returned by your function, it prints the first len elements.使用函数返回的长度,打印出第一个len元素。
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

解答:

 1 class Solution {
 2     public int removeDuplicates(int[] nums) {
 3         int slow=0,fast=0;
 4         while(fast<nums.length){
 5             if(nums[fast]==nums[slow])
 6                 fast++;
 7             else{
 8                 slow++;
 9                 nums[slow]=nums[fast];
10                 fast++;
11             }
12         }
13         return slow+1;
14     }
15 }

详解:

快慢指针。开始两个指针都指向起始位置。

如果两个指针指的数字相同,则快指针向前走一步;

如果不同,则两个指针均向前走一步(先慢指针走一步指向下一个位置,然后将此位置的慢指针所指位置赋值为快指针所指位置,最后快指针向前一步)。

当快指针走到末尾,慢指针当前的坐标加1即为新数组长度也是不同数字的个数(因为从0开始)

猜你喜欢

转载自www.cnblogs.com/chanaichao/p/9588105.html