- 题目链接:https://leetcode.cn/problems/two-sum/
- 1.暴力枚举法-梦开始的地方两数之和
//求两数之和 private static int[] twoSum(int[] arr, int target) { //暴力枚举法 for (int i = 0; i < arr.length; i++) { for (int j = i+1; j < arr.length; j++) { if(arr[i]+arr[j] == target){ //返回两个变量的方法 return new int[]{i,j}; } } } return new int[0]; }
2.哈希法求解两数之和
//求两数之和 private static int[] twoSumHash(int[] arr, int target) { //哈希法 Map<Integer,Integer> map = new HashMap<>(); for (int i = 0; i < arr.length; i++) { map.put(arr[i],i); } //找到下标 for (int i = 0; i < arr.length; i++) { int key = target - arr[i]; if(map.containsKey(key)){ if (i!=map.get(key)){ return new int[]{i,map.get(key)}; } } } return new int[]{}; }
3.测试
public static void main(String[] args) { int[] arr = {3,4,7,6,9,1}; //int [] indexArr = twoSumViolence(arr,12); int [] indexArr = twoSumHash(arr,12); System.out.println(Arrays.toString(indexArr)); }