题记:
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
提示:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
只会存在一个有效答案
**进阶:**你可以想出一个时间复杂度小于 O(n2) 的算法吗?
题目来源:
作者:LeetCode
链接:https://leetcode.cn/leetbook/read/top-interview-questions-easy/x2jrse/
来源:力扣(LeetCode)
官方解题方法:
1,暴力破解法
就是使用两个for循环,这种效率很差
public int[] twoSum(int[] nums, int target) {
int length = nums.length;
for (int i = 0; i < length - 1; i++) {
for (int j = i + 1; j < length; j++)
if (nums[i] + nums[j] == target)
return new int[]{i, j};
}
return new int[]{-1, -1};
}
2,使用HashMap解决
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> m = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (m.get(target - nums[i]) != null) {
return new int[]{m.get(target - nums[i]), i};
}
m.put(nums[i], i);
}
return new int[]{0, 0};
}
方法来源:
作者:数据结构和算法
链接:https://leetcode.cn/leetbook/read/top-interview-questions-easy/x2jrse/?discussion=bsiO6a
来源:力扣(LeetCode)
自己敲的双层for循环方法:
class Solution {
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer[]
*/
function twoSum($nums, $target) {
$length = count($nums);
if($length <= 1){
return false;
}
for($i = 0; $i < $length; $i++){
for($j = $i + 1; $j < $length; $j++){
if($nums[$i] + $nums[$j] == $target){
return array($i,$j);
}
}
}
return [];
}
}
$nums = [2,7,11,15];
$target = 9;
$solution = new Solution();
$result = $solution->twoSum($nums,$target);
print_r($result);
/**
输出结果为:
Array
(
[0] => 0
[1] => 1
)
*/
官方推荐答案:
class Solution {
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer[]
*/
function twoSum($nums, $target) {
$length = count($nums);
if($length <= 1){
return false;
}
//就是先算出target-nums[i],再去和数组里的元素nums[j]比。
//而不是一个个计算nums[i]+[j]再判断是不是和等于target。
//假设一共有n个元素,显然**后者**的计算加法的次数最多为(n-1)+(n-2)+(n-3)+...+3+2+1=n(n-1)/2次;
//而**前者**只需要计算减法最多n-1次;这样优劣就很显然了;
$map = array();
$length = count($nums);
for($i=0; $i < $length; $i++) {
$diff = $target - $nums[$i]; //计算差值
if(isset($map[$diff])) { //将差值作为$map数组的键
return array($i,$map[$diff]);
}
$map[$nums[$i]] = $i; //$nums[$i]值作为$map的键,$i下标作为$map的值
}
return [];
}
}
$nums = [2,7,11,15];
$target = 9;
$solution = new Solution();
$result = $solution->twoSum($nums,$target);
print_r($result);
/**
Array
(
[0] => 2
[1] => 1
)
*/