point: HashMap(key, value) can save nonredundant keys. it's better fit for getting elements quickly.

Title: Add Two Sum。
Requirements:
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.

Input: numbers={2, 7, 11, 15}, target=9
Output: [0, 1]

Analysis:

if we use for-loop twice and calculate all the pairs. it will be up-to timeout.

so we can use map to save the number list. use target - first number and then check last number is in the map or not.

map.get(Object keys) => Object value

Java

public class Leetcode1 {
public static void main(String[] args) {
int[] array = new int[]{2,7,10,13};
int target = 12;
System.out.println(Arrays.toString(twoSum(array, target)));
}

private static int[] twoSum(int[] array, int target) throws IllegalArgumentException {
Map arrays = new HashMap<Integer, Integer>();
for(int i=0; i< array.length; i++) {
arrays.put(array[i], i);
if(arrays.containsKey(target - array[i])&& (Integer)arrays.get(target - array[i])!=i) {
return new int[]{(Integer) arrays.get(target - array[i]), i};
}
}
throw new IllegalArgumentException("no such data");
}
private static int[] twoSumold(int[] array, int target) throws IllegalArgumentException {
Map arrays = new HashMap();
for(int i=0; i<array.length;i++) {
arrays.put(array[i], i);
}
for(int i=0; i<array.length;i++) {
int rest = target - array[i];
if(arrays.containsKey(rest) && (Integer)arrays.get(rest)!=i) {
return new int[]{i, (Integer) arrays.get(rest)};
}
}
throw new IllegalArgumentException("no such data");
}

}

additonal notes:

 

interfacesub interfacesorted?allow redundancy?
Collection             
List    ArrayList
       LinkedList
       Vector
Set AbstractSet
   HashSet
   TreeSet 是(用二叉排序树)
Map AbstractMap 使用key-value来映射和存储数据,key必须唯一,value可以重复
   HashMap  
   TreeMap 是(用二叉排序树) 使用key-value来映射和存储数据,key必须唯一,value可以重复

posted on 2019-05-01 18:22  connie313  阅读(123)  评论(0)    收藏  举报