题解 | #两数之和#
两数之和
https://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param numbers int整型一维数组 * @param target int整型 * @return int整型一维数组 */ public int[] twoSum (int[] numbers, int target) { // write code here int[] res = new int[2]; Map<Integer, Integer> map = new HashMap<>(); for(int i=0; i<numbers.length; i++){ map.put(numbers[i], i+1); } for(int i=0; i<numbers.length; i++){ int temp = target - numbers[i]; if(map.containsKey(temp)){ int val = map.get(temp); if(val != (i+1)){ res[0] = i+1; res[1] = map.get(temp); System.out.println(res[0]); System.out.println(res[1]); break; } } } return res; } }