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
解法
class Solution {
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
* 遍历生成一个类hash数组,然后再遍历原数组,剩余值 = 目标值 - 遍历的数组值,判断类hash数组中存不存在 剩余值 ,如果存在则返回相应的下标
* @return Integer[]
*/
function twoSum($nums, $target) {
$arr = [];
foreach ($nums as $key => $value) {
if (isset($arr[$value])) {
//因为每种输入只会有一种答案,如果有相等的数据,只有可能两数之和和目标值相等,如果不相等则丢弃一个值
if (($value + $value) == $target) {
return [$arr[$value], $key];
}
} else {
$arr[$value] = $key;
}
}
foreach ($nums as $key => $value) {
$leftValue = $target - $value;
if (isset($arr[$leftValue]) && $arr[$leftValue] != $key) {
return [$key, $arr[$leftValue]];
}
}
return [];
}
}
本文介绍了一个高效的解决方案来解决LeetCode上的经典问题“两数之和”。通过使用类hash数组,此方法实现了时间复杂度为O(n)和空间复杂度为O(n)的算法,快速找到数组中和为目标值的两个整数及其下标。

521

被折叠的 条评论
为什么被折叠?



