LeetCode刷题:两数之和
package LeetCode; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class demo01 { public static int[] twoSum(int[] arr,int target){ Map<Integer,Integer> map=new HashMap<>(); //key:数 value:位置(索引) for (int i=0;i<arr.length;i++){ if (map.containsKey(target-arr[i])){ return new int[]{map.get(target-arr[i]),i}; }else { map.put(arr[i],i); } } return new int[]{-1,-1}; //找不到是返回[-1,-1] } public static void main(String[] args) { int[] arr={1,2,8,7,9}; int[] twoSum = twoSum(arr, 10); System.out.println(Arrays.toString(twoSum)); } }