Two Sum

作者: Jun_简书 | 来源:发表于2019-05-08 22:26 被阅读0次

    原题链接-Easy

    Example
    Given nums = [2, 7, 11, 15], target = 9,

    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1]

    时间复杂度: O(N)- 空间复杂度: O(N)

    <?php
    print_r(test([11,2,7,15], 9));
    
    function test($nums, $target) {
        $lookup[$nums[0]] = 1;
        foreach ($nums as $key=>$num) {
            // code...
            if (in_array($target - $num, $nums)) {
                // code...
                return [array_search($target-$num,$nums),$key];
            }else {
                $lookup[$num] = $key;
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Two Sum

          本文链接:https://www.haomeiwen.com/subject/lfyboqtx.html