1. 程式人生 > 實用技巧 >0080. Remove Duplicates from Sorted Array II (M)

0080. Remove Duplicates from Sorted Array II (M)

Remove Duplicates from Sorted Array II (M)

題目

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, 0, 1, 1, 2, 3 and 3 respectively.

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

題意

給定一個有序陣列,要求將陣列中具有重複值的元素依次排在陣列前部,且同一個值對應的元素最多有兩個,返回構成的新陣列的長度。

思路

26. Remove Duplicates from Sorted Array 的基礎上加上了條件:重複元素最多保留兩個。方法也比較簡單:設一個變數count記錄新陣列最後一個元素的重複次數。遍歷原陣列,每次都將當前元素和新陣列的最後一個元素進行比較,如果不同則直接移入新陣列,並將count重置為1;如果相同,判斷count的值,只有當重複次數count=1時才將當前元素移入新陣列,並使count加1。


程式碼實現

Java

class Solution {
    public int removeDuplicates(int[] nums) {
        int p = 0;
        int count = 1;
        
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[p] && count == 1) {
                nums[++p] = nums[i];
                count++;
            } else if (nums[i] != nums[p]) {
                nums[++p] = nums[i];
                count = 1;
            }
        }

        return p + 1;
    }
}

JavaScript

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function (nums) {
  let p = 0, q = 0
  let cur = nums[0], cnt = 0

  for (let num of nums) {
    if (num === cur) {
      cnt++
    } else {
      cur = num
      cnt = 1
    }

    if (cnt <= 2) {
      nums[p++] = nums[q]
    }
    q++
  }

  return p
}