1.哈希映射的用法:
哈希映射是用於存儲 鍵——值對(key, value) 的一種實現。
哈希映射的三個常用方法:
put(key, value):向哈希映射中插入(鍵,值)的數值對。如果鍵對應的值已經存在,更新這個值。
get(key):返回給定的鍵所對應的值,如果映射中不包含這個鍵,返回-1。
remove(key):如果映射中存在這個鍵,刪除這個數值對。
示例:
MyHashMap hashMap = new MyHashMap();
hashMap.put(1, 1);
hashMap.put(2, 2);
hashMap.get(1); // 返回 1
hashMap.get(3); // 返回 -1 (未找到)
hashMap.put(2, 1); // 更新已有的值
hashMap.get(2); // 返回 1
hashMap.remove(2); // 刪除鍵爲2的數據
hashMap.get(2); // 返回 -1 (未找到)
哈希函數的簡單實例:
給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值target的那兩個整數,並返回他們的數組下標。
方法一:暴力破解(省略)
方法二:哈希映射:
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int temp= target - nums[i];
if (map.containsKey(temp)) { //containsKey():用於檢查特定鍵是否被映射到HashMap中。
return new int[] { map.get(temp), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}