LeetCode a daily question (a): the sum of two numbers

Title:
Given an integer array nums and a target value target, and ask you to identify the target value of the two integers in the array, and return to their array subscript.
You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.

Example:
Given nums = [2, 7, 11 , 15], target = 9
because nums [0] + nums [1 ] = 2 + 7 = 9
is returned [0, 1]

Violent solution :( double loop)

class Solution {

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

When executed with 1900 ms, memory consumption 15.8Mb

 

Optimization :( key reversal)

class Solution {

    /**
     * @param Integer[] $nums
     * @param Integer $target
     * @return Integer[]
     */
    function twoSum($nums, $target) {
        $found = [];
        foreach($nums as $key => $val){
            $diff = $target - $val;
            if(!isset($found[$diff])){
                $found[$val] = $key;
                continue;
            }
            return [$key, $found[$diff]];
        }
    }
}

When executed with 12ms, memory consumption 16.1Mb

The first method is the most violent of the most time-consuming, the second method is to use space for time

 

Guess you like

Origin www.cnblogs.com/jongty/p/11653700.html