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:
| interface | sub interface | sorted? | allow redundancy? | 
|---|---|---|---|
| Collection | 否 | ||
| List | ArrayList | 否 | 是 | 
| LinkedList | 否 | 是 | |
| Vector | 否 | 是 | |
| Set | AbstractSet | 否 | 否 | 
| HashSet | 否 | 否 | |
| TreeSet | 是(用二叉排序树) | 否 | |
| Map | AbstractMap | 否 | 使用key-value来映射和存储数据,key必须唯一,value可以重复 | 
| HashMap | 否 | ||
| TreeMap | 是(用二叉排序树) | 使用key-value来映射和存储数据,key必须唯一,value可以重复 | 
                    
                
                
            
        
浙公网安备 33010602011771号