前往
大廳
主題

[LeetCode C#] 26. Remove Duplicates from Sorted - Array

帥氣跳蚤蛋 | 2021-07-11 21:46:47 | 巴幣 0 | 人氣 367

難度: Easy
===========================================================================
說明:
給予nums整數字串,刪除重複的數字,使每個數字只出現一次,數字的相對位置要保持不變,
在刪除重複項後,留有k個數字,則nums須保存k個數字,而之後的數字內容就不重要了,
將最終的結果k個數字放入nums的前k個位置的陣列中,並返回k,
在使用nums的陣列下完成題目,不要開啟新的陣列.
===========================================================================
測資:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
===========================================================================
條件限制:
0<=nums陣列長度<=3*10^4
-100 <= nums[i] <= 100
nums的資料已按遞增進行排序
===========================================================================
解題:
建立一個標示目前儲存位置的count指標,
nums[0]直接放進陣列中,所以count由1開始做儲存,
並開始由nums[1]開始做比較,對整個陣列做搜索,
若與nums[count-1]的數字不同,則儲存至nums[count]的位置,
同時count的位置往下移動,
至整個陣列完成搜索,count的數字,即表示不重複數字的數量.

public class Solution
{
    public int RemoveDuplicates(int[] nums)
    {   
        if (nums.Length == 0)
            return 0;

        int count = 1;  

        for(int i=1;i<nums.Length;i++) //從index[1]開始比較數字
        {
            if (nums[count-1] != nums[i])   //假設數字不同
            {
                nums[count] = nums[i];  //則換上新的數字
                count++;    //在將要儲存的位置往下移
            }
        }
        return count;
    }
}
送禮物贊助創作者 !
0
留言

創作回應

相關創作

更多創作