首页 > 代码库 > Two Sum
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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
Naive Approach:
1 public int[] twoSum(int[] numbers, int target) { 2 //Note this is the naive apporach 3 //the time complexity is n^2. 4 int[] result = new int[2]; 5 for (int i = 0; i < numbers.length; i++) { 6 for (int j = i + 1; j < numbers.length; j++) { 7 if (target == numbers[i] + numbers[j]) { 8 //Note 9 result[0] = i + 1; 10 result[1] = j + 1; 11 return result; 12 } 13 } 14 } 15 return result; 16 }
Using Hash-Map
1 public int[] twoSum(int[] numbers, int target) { 2 int[] result = new int[2]; 3 HashMap<Integer,Integer> map = new HashMap<Integer, Integer>(); 4 for(int i= 0;i<numbers.length;i++){ 5 if(map.containsKey(numbers[i])){ 6 result[0]=map.get(numbers[i]); 7 result[1]=i+1; 8 } 9 else { 10 map.put((target-numbers[i]),i+1); 11 } 12 } 13 return result; 14 }
Basic method of HashMap
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Modifier and Type | Method and Description |
---|---|
void | clear() Removes all of the mappings from this map. |
Object | clone() Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned. |
boolean | containsKey(Object key) Returns true if this map contains a mapping for the specified key. |
boolean | containsValue(Object value) Returns true if this map maps one or more keys to the specified value. |
Set<Map.Entry<K,V>> | entrySet() Returns a Set view of the mappings contained in this map. |
V | get(Object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
boolean | isEmpty() Returns true if this map contains no key-value mappings. |
Set<K> | keySet() Returns a Set view of the keys contained in this map. |
V | put(K key, V value) Associates the specified value with the specified key in this map. |
void | putAll(Map<? extends K,? extends V> m) Copies all of the mappings from the specified map to this map. |
V | remove(Object key) Removes the mapping for the specified key from this map if present. |
int | size() Returns the number of key-value mappings in this map. |
Collection<V> | values() Returns a Collection view of the values contained in this map. |
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。