标签:
Two Sum
问题:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
思路:
hashtable
我的代码:
public class Solution { public int[] twoSum(int[] numbers, int target) { HashMap<Integer,Integer> save = new HashMap<Integer,Integer>(); HashMap<Integer,Integer> duplicate = new HashMap<Integer,Integer>(); for(int i = 0; i < numbers.length; i++) { if(save.containsKey(numbers[i])) { duplicate.put(numbers[i],i+1); } else { save.put(numbers[i],i+1); } } int[] rst = new int[2]; for(int i = 0; i < numbers.length; i++) { int val = numbers[i]; int remain = target - val; if(val == remain) { if(duplicate.containsKey(val)) { rst[0] = i+1; rst[1] = duplicate.get(val); return rst; } continue; } if(save.containsKey(remain)) { rst[0] = i+1; rst[1] = save.get(remain); return rst; } } return rst; } }
他人代码:
public int[] twoSum(int[] numbers, int target) { int[] result = new int[2]; Hashtable<Integer, Integer> table = new Hashtable<Integer, Integer>(); for(int i = 0; i < numbers.length; i++){ if(table.containsKey(numbers[i])){ result[0] = table.get(numbers[i]) + 1; result[1] = i + 1; } table.put(target - numbers[i], i); } return result; }
学习之处:
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4335125.html