算法題丨Remove Duplicates from Sorted Array II

描述

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?git

示例

Given sorted array 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. It doesn't matter what you leave beyond the new length.

算法分析

難度:中
分析:條件參考Remove Duplicates算法,只不過以前元素只容許重複1次,如今改成最多能夠重複2次。
思路:既然輸入的數組排好序的,那咱們定義一個有效元素的數組長度變量i,而後開始遍歷元素:
 1. 檢索當前元素以前的2個元素,若是跟當前元素相等,說明不知足最多重複2次的條件了,這時候有效元素的數組長度i就不要再自增了;
 2. 不然的話,以前的2個元素,如跟當前元素不相等(小於),說明這個當前元素爲有效值,因此將數組末尾元素賦值當前元素,有效元素的數組長度i自增1;
依照上述邏輯循環判斷,一直到數組最後一個元素,循環結束後,根據有效元素的數組長度i,得到[0,i)範圍內的數組元素,即爲題目要求的結果。github

代碼示例(C#)

public int RemoveDuplicates2(int[] nums)
{
    int i = 0;
    foreach (var num in nums)
    {
        //判斷是否有2個以上重複,有的話有效索引+1,並將當前元素賦值到有效數組
        if (i < 2 || num > nums[i - 2])
            nums[i++] = num;
    }
    return i;
}

複雜度

  • 時間複雜度O (n).
  • 空間複雜度O (1).

附錄

相關文章
相關標籤/搜索