Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
两数之和
给定一个整数数组和一个目标值,在数组中找出和为目标值的那两个整数,并返回这两个数的数组下标。
可以假设每个输入都会有唯一解,并且一个元素只能用一次。
function twoSum($arr, $target) {
for ($i = 0; $i < count($arr) - 1; $i++) {
for ($j = $i + 1; $j < count($arr); $j++) {
if ($arr[$i] + $arr[$j] == $target) {
echo "两个数分别为 $arr[$i] 和 $arr[$j],其对应的下标为 $i 和 $j";
exit;
}
}
}
echo "无解";
}
$arr = [12, 3, 11, 6];
$target = 9;
twoSum($arr, $target);
原文:https://www.cnblogs.com/sunshineliulu/p/12254201.html