1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| package top.hopestation;
import java.util.Arrays; import java.util.HashMap; import java.util.Map;
public class LeetCode { public static int[] twoSum1(int[] nums, int target) { int len = nums.length; for (int i = 0; i <len ; i++) { if(nums[i]>target){ continue; } for (int j = i+1; j < len; j++) { if(nums[i] + nums[j] == target){ return new int[]{i,j}; } } } return null; }
public static int[] twoSum2(int[] nums, int target) { Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; ++i) { if (hashtable.containsKey(target - nums[i])) { return new int[]{hashtable.get(target - nums[i]), i}; } hashtable.put(nums[i], i); } return new int[0];
}
public static void main(String[] args) { int[] param = {1,2,5,3,4,7,}; String res = Arrays.toString(twoSum2(param, 10)); System.out.println(res); } }
|