话不多说直接看,
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
给定一个示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解题思路如下:
//创建一个类
class Index
{
//定义变量
public $num = null;
public $target = null;
//用的是leetcode上面的例子,但是数组值不一样,其实原理一样
public function __construct(Request $request = null)
{
$this->num = [4, 7, 6, 15];
$this->target = 13;
}
//直接运行此方法
public function getNum()
{
foreach($this->num as $key => $value)
{
$newNum = $this->target - $value;
if(isset($arr[$newNum]) && $this->num[$arr[$newNum]] + $value === $this->target){
return [$arr[$this->target - $value], $key];
}
$arr[$value] = $key;
}
}
}此时的运行结果是 [1, 2]
在leetcode原题中的它是按顺序加的,但是我之前写的方法是反过来的,不知道这样子做是不是错的,如果没有规定返回的顺序,我想应该也是对的,如果要求从左到右的顺序,那就是错的,主要区别于下面的函数
public function getNum()
{
foreach($this->num as $key => $value)
{
$newNum = $this->target - $value;
if(isset($arr[$newNum]) && $this->num[$arr[$newNum]] + $value === $this->target){
return [$arr[$this->target - $value], $key];
}
//主要是这一步
$arr = array_flip($this->num);
}
}这种方法运行出来结果是 [2, 1],主要就是调整键值对位置的时候,使用的是array_flip数组函数
