题目
题目链接:
https://www.nowcoder.com/practice/390da4f7a00f44bea7c2f3d19491311b
思路
map
参考答案C++
#include <vector>
class Solution {public:vector<int> FindNumbersWithSum(vector<int> array, int sum) {vector<int> ans;map<int, int> map1;for (int i = 0; i < array.size(); i++) {auto it = map1.find(sum - array[i]);if (it != map1.end()){if(it->first == sum-array[i]){ans.push_back(sum-array[i]);ans.push_back(array[i]);break;} }map1[array[i]] = array[i];}return ans;}
};
参考答案Java
import java.util.*;
import java.util.ArrayList;
public class Solution {public ArrayList<Integer> FindNumbersWithSum(int [] array, int sum) {ArrayList<Integer> ans = new ArrayList<>();Map<Integer, Integer> map = new HashMap<>();for (int v : array) {if (map.containsKey(sum - v)) {ans.add(sum - v);ans.add(v);break;}map.put(v, v);}return ans;}
}
参考答案Go
package main/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可* * @param array int整型一维数组 * @param sum int整型 * @return int整型一维数组
*/
func FindNumbersWithSum( array []int , sum int ) []int {ans:=[]int{}map1:=map[int]int{}for _,v:=range array {_,exist:= map1[sum-v] if exist {ans= append(ans, sum-v)ans=append(ans, v)break}map1[v]=v}return ans
}
参考答案PHP
<?php/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可* * @param array int整型一维数组 * @param sum int整型 * @return int整型一维数组*/
function FindNumbersWithSum( $array , $sum )
{$ans = [];$map = [];foreach($array as $v){if(isset($map[$sum-$v])){$ans[0] = $sum-$v;$ans[1] = $v;break;}$map[$v] = $v;}return $ans;
}