Two Sum
題目描述
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, and you may not use the same element twice
Example
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
中文描述
給定一個數組和一個目標值,返回和為目標值的兩個數的索引值。假設每一個輸入都有一個確定結果,同一個元素無法使用兩次
解題方案
- 首先想到的就是brute force算法,兩層的循環解決問題,時間復雜度為O(n),空間復雜度為常數。代碼如下
public int[] twoSum(int[] nums, int target) {
int[] answer= new int[2];
for(int i=0;i<nums.length;i++){
answer[0]=nums[i];
int temp = target-answer[0];
for(int j=i;j<nums.length;j++){
if(nums[j]==temp){
return answer;
}
}
}
return answer;
}
- 第二種方案就是考慮如何優化上一種算法了,這里看到網上的采用HashMap的方式來優化算法的時間復雜度。
利用的是HashMap取數據時間是常數時間。
public int[] twoSum2(int[] nums, int target) {
int[] res = new int[2];
if(numbers==null||numbers.length<2) return null;
Map<Integer, Integer> map = new HashMap<>();
for(int i=0;i<numbers.length;i++){
if(map.containsKey(target-numbers[i])){
res[0]=map.get(target-numbers[i])+1;
res[1]=i+1;
return res;
}
map.put(numbers[i],i);
}
return null;
}
因為之前對于Java集合類的基礎了解不夠,所以不太理解所謂的HashMap取值操作為常數時間。于是查閱了相關資料,現記錄一下。
Java HashMap 是基于哈希表的Map接口實現,以Key-Value的形式在HashMap中,key-value總是會當做一個整體來處理,系統會根據hash算法來來計算key-value的存儲位置,我們總是可以通過key快速地存、取value。下面就來分析HashMap的存取。
HashMap的構造函數
HashMap():
構造一個具有默認初始容量 (16) 和默認加載因子 (0.75) 的空 HashMap。
HashMap(int initialCapacity):
構造一個帶指定初始容量和默認加載因子 (0.75) 的空 HashMap。
HashMap(int initialCapacity, float loadFactor):
構造一個帶指定初始容量和加載因子的空 HashMap。
其中關于初始容量和加載因子和其他數據結構的概念相同,初始容量是創建哈希表d額初始大小,加載因子表示哈希表的最大填充程度。也就是當哈希表達到這個填充程度的時候,就需要對哈希表進行擴容。
HashMap存儲
下面簡單看一下hashMap的put方法源碼
public V put(K key, V value) {
//當key為null,調用putForNullKey方法,保存null與table第一個位置中,這是HashMap允許為null的原因
if (key == null)
return putForNullKey(value);
//計算key的hash值
int hash = hash(key.hashCode()); ------(1)
//計算key hash 值在 table 數組中的位置
int i = indexFor(hash, table.length); ------(2)
//從i出開始迭代 e,找到 key 保存的位置
for (Entry<K, V> e = table[i]; e != null; e = e.next) {
Object k;
//判斷該條鏈上是否有hash值相同的(key相同)
//若存在相同,則直接覆蓋value,返回舊value
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value; //舊值 = 新值
e.value = value;
e.recordAccess(this);
return oldValue; //返回舊值
}
}
//修改次數增加1
modCount++;
//將key、value添加至i位置處
addEntry(hash, key, value, i);
return null;
}
通過源碼我們可以清晰看到HashMap保存數據的過程為:首先判斷key是否為null,若為null,則直接調用putForNullKey方法。若不為空則先計算key的hash值,然后根據hash值搜索在table數組中的索引位置,如果table數組在該位置處有元素,則通過比較是否存在相同的key,若存在則覆蓋原來key的value,否則將該元素保存在鏈頭(最先保存的元素放在鏈尾)。若table在該處沒有元素,則直接保存。保存的過程看起來十分簡單,但是其中有一部分比較重要的就是求Hash值函數
static int hash(int h) {
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
對于HashMap的table而言,數據分布需要均勻(最好每項都只有一個元素,這樣就可以直接找到),不能太緊也不能太松,太緊會導致查詢速度慢,太松則浪費空間。計算hash值后,怎么保證數據的分布呢?HashMap調用indexFor方法。
static int indexFor(int h, int length) {
return h & (length-1);
}
這個函數我在一開始沒有理解到底什么意思,通過看別人的講解后發現這個函數的作用和取模運算是相同的。具體計算的結果可以看下面的表格。
h | length-1 | h&length-1 | result |
---|---|---|---|
0 | 14 | 0000&1110=0000 | 0 |
1 | 14 | 0001&1110=0000 | 0 |
2 | 14 | 0010&1110=0010 | 2 |
3 | 14 | 0011&1110=0010 | 2 |
4 | 14 | 0100&1110=0100 | 4 |
5 | 14 | 0101&1110=0100 | 4 |
6 | 14 | 0110&1110=0110 | 6 |
7 | 14 | 0111&1110=0110 | 6 |
8 | 14 | 1000&1110=1000 | 8 |
9 | 14 | 1001&1110=1000 | 8 |
10 | 14 | 1010&1110=1010 | 10 |
11 | 14 | 1011&1110=1010 | 10 |
12 | 14 | 1100&1110=1100 | 12 |
13 | 14 | 1101&1110=1100 | 12 |
14 | 14 | 1110&1110=1110 | 14 |
15 | 14 | 1111&1110=1110 | 14 |
從上面的圖表中我們看到總共發生了8此碰撞,同時發現浪費的空間非常大,有1、3、5、7、9、11、13、15處沒有記錄,也就是沒有存放數據。這是因為他們在與14進行&運算時,得到的結果最后一位永遠都是0,即0001、0011、0101、0111、1001、1011、1101、1111位置處是不可能存儲數據的,空間減少,進一步增加碰撞幾率,這樣就會導致查詢速度慢。而當length = 16時,length – 1 = 15 即1111,那么進行低位&運算時,值總是與原來hash值相同,而進行高位運算時,其值等于其低位值。所以說當length = 2^n時,不同的hash值發生碰撞的概率比較小,這樣就會使得數據在table數組中分布較均勻,查詢速度也較快。
讀取的實現
相對于HashMap的存而言,取就顯得比較簡單了。通過key的hash值找到在table數組中的索引處的Entry,然后返回該key對應的value即可。
public V get(Object key) {
// 若為null,調用getForNullKey方法返回相對應的value
if (key == null)
return getForNullKey();
// 根據該 key 的 hashCode 值計算它的 hash 碼
int hash = hash(key.hashCode());
// 取出 table 數組中指定索引處的值
for (Entry<K, V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
Object k;
//若搜索的key與查找的key相同,則返回相對應的value
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}
從上面的代碼當中我們就可以得到為什么HashMap可以以常數的時間進行存取數據了。
再寫這篇文章的時候,在CSDN的博客發現了另外的解法,
先對數組進行排序,然后使用夾逼的方法找出滿足條件的pair,原理是因為數組是有序的,那么假設當前結果比target大,那么左端序號右移只會使兩個數的和更大,反之亦然。所以每次只會有一個選擇,從而實現線性就可以求出結果。該算法的時間復雜度是O(nlogn+n)=O(nlogn),空間復雜度取決于排序算法。
public int[] twoSum(int[] numbers, int target) {
int[] res = new int[2];
if(numbers==null || numbers.length<2)
return null;
Arrays.sort(numbers);
int l = 0;
int r = numbers.length-1;
while(l<r)
{
if(numbers[l]+numbers[r]==target)
{
res[0] = number[l];
res[1] = number[r];
return res;
}
else if(numbers[l]+numbers[r]>target) r--;
else l++;
}
return null;
}
參考鏈接
項目GitHub鏈接
https://github.com/yanqinghe/leetcode/blob/master/leetcodeJava/src/Two_Sum_1/Solution.java
PS:寫在后面,現在開始補寫文檔記錄刷leetcode的過程,也希望能把自己的想法記錄下來與別人分享,同時也希望能夠與更多的人交流。
GitHub主頁https://github.com/yanqinghe/leetcode