算法題丨Remove Duplicates from Sorted Array

描述

Given a sorted array, 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.git

示例

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 new length.

算法分析

難度:低
分析:要求給定的排序後的數組,將其中重複的元素去除(是的每一個元素只出現一次),並返回最終數組的長度。算法不要分配額外的數組空間。
思路:既然輸入的數組已然排好序,咱們能夠定義i,j兩個數組下標值,開始i初始爲0,用來記錄數組中有效元素下標,j從1開始,用來記錄遍歷數組的下標:
若是數組[j]==數組[i],表示有重複,重複元素個數i不用累計,遍歷數組下一條;
若是數組[j]!=數組[i],表示沒有重複,有效元素下標i自增+1,把數組[i]值用數組[j]替代,比較下一個元素;
依次遍歷,直到數組[j]至最後一個元素,最終[0,i]範圍內的數組元素,即爲題目要求的結果。github

代碼示例(C#)

public int RemoveDuplicates(int[] nums)
{
    if (nums.Length == 0) return 0;
    int i = 0;
    for (int j = 1; j < nums.Length; j++)
    {
        //不重複的話,有效索引+1,將當前元素值記錄在索引對應的數組上
        if (nums[j] != nums[i])
        {
            i++;
            nums[i] = nums[j];
        }
    }
    return i + 1;
}

複雜度

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

附錄

相關文章
相關標籤/搜索