题解 | #两数之和#
两数之和
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) { int[] arr=new int[2]; Map<Integer,Integer> map=new HashMap<>(); for(int i=0;i<numbers.length;i++){ if(map.containsKey(numbers[i])){ if(numbers[i]*2==target){ arr[0]=map.get(numbers[i])+1; arr[1]=i+1; return arr; } } map.put(numbers[i],i); } for(int i=0;i<numbers.length;i++){ int val=target-numbers[i]; if(map.containsKey(val)){ if(target-numbers[i]==numbers[i]){ continue; }else{ arr[0]=i+1; arr[1]=map.get(val)+1; break; } } } return arr; } }