Q:
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].
A:
Brute Force,時間復(fù)雜度為O(n??^2)。
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (nums[i] = target - nums[j]) {
return new int[] {i,j}; //直接new一個新的返回
}
}
}
throw new IllegalArgumentException ("No Match");
}
HashTable,時間復(fù)雜度為O(n)。
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
// containsKey的復(fù)雜度是O(1),containsValue的復(fù)雜度是O(n)
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
單次跑Hashmap,找到就彈出結(jié)果,不繼續(xù)put后面的進(jìn)Hashmap了。精煉!
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
//第一遍還是空的,什么都不做,下面put一次!
//這個 containsKey 方法返回值是boolean, true if mapping
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
//put先執(zhí)行一次,別的再說
map.put(nums[i], i); //key和value這里是反著的,因為最后要按index值輸出
}
throw new IllegalArgumentException("No two sum solution");
}
Notes:
時間復(fù)雜度 計算方法
.
看看有幾重for循環(huán),
只一重,為O(n),
二重,為O(n^2),
有二分,為O(logn),
一個for循環(huán)套一個二分,為O(nlogn)。
HashTable vs HashMap
.
HashMap比HashTable新,儲存鍵值對象(Key Value),可以接受null,非synchronized。
沒有正確同步的時候,多個線程不能正確共享HashMap。同步方法為:
Map m = Collections.synchronizeMap(hashMap);
.
如果一個類沒有重寫hash方法,那么就是默認(rèn)使用Object的hash方法。
.
一個Key只能映射一個Value,賦值同個Key,后來的,覆蓋之前的。
Map vs HashMap
.
Map :是Interface 接口 JAVA API: Class HashMap <Key, Value>
HashMap :是class 實現(xiàn)類 JAVA API: Interface Map <Key, Value>
只能訪問Map定義的方法和屬性:
Map map1 = new Hashmap();
可以訪問到HashMap定義的方法和屬性:
Map map = (Map)map2; //這又回去了,只能訪問Map的了````
Hashmap是子類,它自己定義了一堆方法。
.
Map中要的是對象 <Object, Object>
不能使用基本類型(比如int),Integer
可以。
如果 map.put (1,“123”)
,會自動封裝,map.put(new Integer(1), "123");
Java Collection Framework (和Hash相關(guān)的)
.
HashSet和HashMap實現(xiàn)的是不同接口。
TreeMap的對象是Sorted,HashMap不是,用的時間長了好像次序也會亂,保證不了。