HashMap常用方法
- add element: map.put(key, value)
- from key get value: map.get(key)
- Build HashMap: getOrDefault
- iterate HashMap: for(? i:map.keySet())
- String HashMap
1512. Number of Good Pairs
Given an array of integers nums.
A pair (i,j) is called good if nums[i] == nums[j] and i < j.
Return the number of good pairs.
Example 1:
Input: nums = [1,2,3,1,1,3] Output: 4 Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
class Solution {
public int numIdenticalPairs(int[] nums) {
int res = 0;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
//calculate count for each key
for(int x : nums){
map.put(x, map.getOrDefault(x, 0)+1);
}
//iterate
for(Integer i : map.keySet()){
System.out.println("key: " + i + "value: " + map.get(i));
}
for(Integer i : map.keySet()){
if(map.get(i) > 1){
int n = map.get(i);
for(int j = 1; j <= n-1; j++){
res += j;
}
}
}
return res;
}
}
- Build HashMap: getOrDefault
- iterate HashMap: for(? i:map.keySet())
771. Jewels and Stones
You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so "a" is considered a different type of stone from "A".
Example 1:
Input: jewels = "aA", stones = "aAAbbbb" Output: 3
class Solution {
public int numJewelsInStones(String jewels, String stones) {
int res = 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for(char x : jewels.toCharArray()){
map.put(x, 0);
}
for(char x: stones.toCharArray()){
if(map.containsKey(x)){
map.put(x, map.getOrDefault(x, 0)+1);
res += 1;
}
}
return res;
}
}
- String HashMap
1. Two Sum
Example 1:
Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1].
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] defaultResult = {0, 0};
for (int i = 0; i < nums.length; i++) {
if (map.get(target-nums[i]) != null ) {
int[] result = {map.get(target-nums[i]), i };
return result;
}
map.put(nums[i], i);
}
return defaultResult;
}
}
- how to prevent duplicate e.g. nums=[3, 3], target = 6, Output = [0, 1]