iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 5
0
自我挑戰組

刷題記錄與人生分享系列 第 5

DAY5 Remove Duplicates from Sorted Array

題目:

https://leetcode.com/problems/remove-duplicates-from-sorted-array/
一個排列好的陣列,回傳差異整數的長度。

解題思路:

先判斷陣列長度,利用for迴圈探索中用一個變數紀錄目前長度並當成替代的索引值,但因從索引一開始探索因此要在回傳時將變數紀錄加一。

C版本:

int removeDuplicates(int* nums, int numsSize) {
    if (numsSize == 0) 
     return 0;
    int i=0,j;
    for(j=1; j<numsSize; j++ )
    {
        if(nums[j] != nums[i])
        {
            i++;
            nums[i] = nums[j];
        }
    }
    return i+1;
}

Javascript版本:

var removeDuplicates = function(nums) {
    if(nums == null || nums.length == 0) return 0;
    if(nums.length == 1) return 1;
    var count = 0;
    for(var i = 1 ; i < nums.length ; i++){
        if(nums[count] != nums[i]){
            count++;
            nums[count] = nums[i];
        }
    }    
    return ++count;
};

程式Github分享:

https://github.com/SIAOYUCHEN/leetcode

相似主題分享:

https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136

本日分享:

Life is a multiple-choice question; often what confuses you is not the question, but the options available.
人生就像一道選擇題,往往讓你困惑的不是題目,而是選項


上一篇
DAY 4 Valid Parentheses
下一篇
DAY6 Remove Element
系列文
刷題記錄與人生分享34
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言