A small algorithm

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.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/two-sum
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

 

Example:

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

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

class Solution {

    /**
     * @param Integer[] $nums
     * @param Integer $target
     * @return Integer[]
     */


    function twoSum()
    {
        $nums   = [2, 7, 11, 15];
        $ore_nums = $nums;
        $target = 9;
        $arr = [];
        for ($i = 0; $i <= count($nums); $i++){
            $diff = $target - $nums[$i];
            if(array_key_exists($diff,$nums)){
                return $arr = [$nums[$i],$diff];
            }
        }
        return $arr;
    }


}

  

Guess you like

Origin www.cnblogs.com/computer-technology/p/11963048.html