Description
Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution.
Example
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
MySolution
//时间复杂度 O(n)
//空间复杂度 O(n)
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> hm=new
HashMap<Integer,Integer>();
int[] res=new int[2];
for(int i=0;i<nums.length;i++){
if(hm.get(nums[i])==null)
hm.put(target-nums[i],i);
else{
res[0]=hm.get(nums[i]);
res[1]=i;
break;
}
}
return res;
}
}
Discussion
在java中, hm.get(nums[i])的时间复杂度是O(1),但是在C++中似乎不是;
如果有duplicate solution的话,如何改进?
上面的方法,如果有duplicate solution, 会输出第一组解,如果for循环中没有break语句,会输出最后一组解。
但是,如果想要输出全部的解,这边先留白,二刷lc的时候再回来解答。HashMap知道Key值如何得到Value值?
用get(Key)方法如何判断某一个Key值是否存在于HashMap中?
方法一:get(Key)==null 真:不存在 假:存在
方法二:containsKey(Key) 真:存在 假:不存在HashMap知道Value值如何得到Key值?
遍历
import java.util.*;
public class HMTester{
public static void main(String[] args){
Map<String, String> map = new HashMap<String, String>();
map.put("1","value1");
map.put("2","value2");
map.put("3","value3");
//第一种
System.out.println("通过Map.keySet遍历key和value:");
for(String key: map.keySet()){
System.out.println("key= "+key+" and value= "+map.get(key));
}
/**
通过Map.keySet遍历key和value:
key= 3 and value= value3
key= 2 and value= value2
key= 1 and value= value1
*/
//第二种
System.out.println("通过Map.entrySet使用iterator遍历key和value: ");
Iterator<Map.Entry<String,String>> it=map.entrySet().iterator(); //entrySet() Returns a Set view of the mappings contained in this map.
while(it.hasNext()){
Map.Entry<String, String> entry=it.next();
System.out.println("key= "+entry.getKey()+" and value= "+entry.getValue());
}
//第三种 Recommend!!!
System.out.println("通过Map.entrySet遍历key和value");
for(Map.Entry<String, String> entry: map.entrySet()){
System.out.println("key= "+entry.getKey()+" and value= "+entry.getValue());
}
//第四种
System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
for(String v: map.values()){
System.out.println("value= "+v);
}
}
}