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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

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