用 Hash Table 实现
Time : O(n)
Space: O(n)
import java.util.HashMap; public class Solution { public int[] twoSum(int[] nums, int target) { HashMap< Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(target-nums[i])) { int[] result = {map.get(target-nums[i])+1, i+1}; return result; } map.put(nums[i], i); } return null; } public static void main(String[] args) { Solution solu = new Solution(); int[] a = {2, 7, 11, 15}; int target = 9; int[] result = solu.twoSum(a, target); for (int i = 0; i < result.length; i++) System.out.println(result[i]); } }
2015-10-13