1. 两数之和
https://leetcode-cn.com/problems/3sum/
package 数组; import java.util.Arrays; import java.util.HashMap; public class 两数之和 { public static void main(String[] args) { int[] nums = {3, 2, 4}; 两数之和 两数之和 = new 两数之和(); int[] result = 两数之和.twoSum(nums, 6); System.out.println(Arrays.toString(result)); } // 方法一:暴力循环:target减去遍历到的数,去数组找另一个数 public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; if (nums == null || nums.length == 0) { return null; } HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); } for (int i = 0; i < nums.length; i++) { int other = target - nums[i]; if (map.containsKey(other) && map.get(other) != i) { result[0] = i; result[1] = map.get(other); return result; } } return null; } }