天天看点

80. Remove Duplicates from Sorted Array II

80. Remove Duplicates from Sorted Array II

这个题就是走 下 这个 1111111111112222222222233333333333344444456 这个例子会了, 多走几遍
class Solution {
    public int removeDuplicates(int[] nums) {
      int slow = 2;
      for(int fast = 2; fast < nums.length; fast++){
        if(nums[fast] == nums[slow - 2]){
          continue;
        }
        nums[slow] = nums[fast];
        slow++;
      }
      return slow;
    }
}




*  i = 1;
*  j = ++i;
*  (i is 2, j is 2)

* i++ will increment the value of i, but return the original value that i held before being incremented.
 i = 1;
*  j = i++;
*  (i is 2, j is 1)      

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice 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.

Example 1:

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

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

It doesn't matter what you leave beyond the returned length.      

Example 2:

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

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

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

Clarification:

// 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]);
}