leetCode刷題記錄--兩數之和

leetCode題目入下:

給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。

你可以假設每種輸入只會對應一個答案。但是,數組中同一個元素不能使用兩遍。

示例:

給定 nums = [2, 7, 11, 15], target = 9

因爲 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/two-sum
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

 

 

個人解題:

一臉矇蔽的寫出解題方案,遍歷相加,去除相同的k,然後輸出。缺點太耗時!!!

class Solution {

    /**
     * @param Integer[] $nums
     * @param Integer $target
     * @return Integer[]
     */
    function twoSum($nums, $target) {
        for($i = 0; $i < count($nums); $i++){
            for($j = $i+1; $j < count($nums); $j++){
                if($nums[$i] + $nums[$j] === $target && $i != $j) {
                    return [$i, $j];
                }
            }
        }
    }
}

向大佬學習

看看大佬的寫法:

class Solution {

    /**
     * @param Integer[] $nums
     * @param Integer $target
     * @return Integer[]
     */
    function twoSum($nums, $target) {
        $scanned = [];//建立一個搜尋表

        for ($i = 0; $i < count($nums); $i++) {
            $diff = $target - $nums[$i];//當前數字與目標值的差

            if (array_key_exists($diff, $scanned)) {//搜尋表中找到與差相同的值,則返回其index
                return [$scanned[$diff], $i];
            }

            $scanned[$nums[$i]] = $i;//把掃描過的數字其index和值存入搜尋表中
        }

    }
}

作者:da-nan-3
鏈接:https://leetcode-cn.com/problems/two-sum/solution/phpde-you-shi-by-da-nan-3/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章