原题链接在这里:https://leetcode.com/problems/two-sum/
Time Complexity: O(n). Space: O(n).
AC Java:
1 public class Solution { 2 public int[] twoSum(int[] nums, int target) { 3 if(nums == null || nums.length < 2){ 4 return new int[]{-1,-1}; 5 } 6 7 int [] res = new int[]{-1,-1}; 8 Map<Integer, Integer> hm = new HashMap<Integer, Integer>(); 9 10 for(int i = 0; i<nums.length; i++){ 11 if(!hm.containsKey(target-nums[i])){ 12 hm.put(nums[i],i); 13 }else{ 14 res[0] = hm.get(target - nums[i])+1; 15 res[1] = i+1; 16 break; 17 } 18 } 19 return res; 20 } 21 }
原文:http://www.cnblogs.com/Dylan-Java-NYC/p/5040710.html