iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 13
0
自我挑戰組

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

DAY13 Two Sum II - Input array is sorted

題目:

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
在已排序的陣列使其數值相加等於目標值,並返回其索引但須注意並非從0開始。

解題思路:

利用2個for迴圈判斷其相加是否等於目標值,但須注意因為並非從0開始所以在其得到索引位置後都需加一。

C版本:

int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) {
    int *reval = (int*)malloc(sizeof(int)*2);
    *returnSize = 2;
    
    int left, right;
    left = 0; right = numbersSize-1;
    for(;;) {
        if(numbers[left] + numbers[right] > target)
            right--;
        else if(numbers[left] + numbers[right] < target)
            left++;
        else {
            reval[0] = left+1;
            reval[1] = right+1;
            return reval;
        }   
    } 
}

Javascript版本:

var twoSum = function(numbers, target) {
    var result = [];
    for(var i = 0; i<numbers.length; i++)
    {
        for(var j = i+1; j<numbers.length; j++)
        {
            if((numbers[i] + numbers[j]) == target)
            {
                result.push(i+1)
                result.push(j+1)
                return result;
            }
        }
    }
};

程式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

本日分享:

Every time you encounter frustration, when you meet people who laugh at you and hit you, please tell yourself you can’t borrow their wings and fly to the sky you want to go, just like they can’t replace you that living a life you don’t want.
每次遇到挫折的時候、遇到那些嘲笑你和打擊你的人的時候, 請告訴自己,你沒有辦法借他們的翅膀,飛向你想去的天空, 就像他們無法代替你,過你不想要的人生。


上一篇
DAY12 Maximum Product Subarray
下一篇
DAY14 Rotate Array
系列文
刷題記錄與人生分享34
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言