線性搜索:哈希表數組
給定一個整數數組和一個目標值,找出數組中和目標值的兩個數。你能夠假設每一個輸入只對應一種答案,且一樣的元素不能被重複利用。示例:bash
給定 nums = [2, 7, 11, 15], target = 9
由於 nums[0] + nums[1] = 2 + 7 = 9
因此返回 [0, 1]
複製代碼
按題意,對一個數組元素,需找到另外一個互補數。問題的本質是,查找指定值是否存在於數組中。查找問題,理應想到查找爲O(1) 複雜度的哈希表。數據結構
遍歷數組將 元素值=>索引 的映射關係寫入 map,以後遍歷查找互補的數。實現:ui
// 方法一:兩遍哈希遍歷
private 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 j = 0; j < nums.length; j++) {
int complement = target - nums[j];
if (map.containsKey(complement) && map.get(complement) != j) {
return new int[]{j, map.get(complement)};
}
}
throw new IllegalArgumentException("No two sum solution");
}
// 一遍哈希表
public int[] twoSum2(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
複製代碼
理解並抽象出本質,再選擇最爲合適的數據結構實現。spa
哈希表的增刪查複雜度都是O(1)級別的,十分適合線性查找的問題。code