实例化:Map<参数一,参数二> hash = new HashMap<参数一,参数二> //键值对形式
hash.put(key,value) 以键-值对的形式进行put
hash.size() 返回表的长度,记得size后有()
hash.get(key) 返回键值key所对应的value//如果key不存在,那么返回null(boolean类型),一般还是getOrDefault()用的多
hash.getOrDefault(key2,自定义值)
在表里查找是否存在key2这个关键字,若存在返回key2所对应的value,不存在返回自定义的值
注:不能尾追++,一般采用hash.getOrDefault(key2,0)+1
hash.remove(key) 移出关键字key(key和value都没啦)
hash.containsKey() 若查询的k在hash表中存在则返回true,否则false
没有hash.contains()这个方法
for(Map.Entry<Integer , Integer> entry : map.entrySet()){} 遍历Map
map.entrySet() 这里要注意!!!
Map.Entry
对象有两个方法:getKey()
和 getValue()
,分别用于获取键和值。
心得:
1:暴力枚举可以先固定第一个元素,然后去遍历这个元素前面的。
2:常规暴力枚举,是先把这个元素之后所有的元素都放入hash表中,但是有一种情况是会在hash表中自己找到自己。
罗里吧嗦的代码
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hash = new HashMap<>();
int[] targetGroup = new int[2];
for (int i = 0, j = 0; i < nums.length; i++) {
int temp = target - nums[i];
Integer result = hash.get(temp);
if (result != null) {
targetGroup[j] = result;
j++;
targetGroup[j] = i;
}
hash.put(nums[i], i);
}
return targetGroup;
}
}
清爽简洁的代码
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer , Integer> hash = new HashMap<>();
for(int i = 0 ; i < nums.length ; i++){
int tem = target - nums[i];
if(hash.containsKey(tem)){
return new int[]{hash.get(tem),i};
}
hash.put(nums[i],i);
}
return new int[]{1};
}
}
简单题
两种思路,三次遍历or一次遍历增一次遍历减
class Solution {
public boolean isAnagram(String s, String t) {
int[] nums1 = new int[26];
int[] nums2 = new int[26];
for(int i = 0 ; i < s.length() ; i++){
int index = s.charAt(i)- 'a';
nums1[index]++;
}
for(int i = 0 ; i < t.length() ; i++){
int index = t.charAt(i)- 'a';
nums2[index]++;
}
for(int i = 0 ; i < nums1.length ; i++ ){
if(nums1[i] != nums2[i]){
return false;
}
}
return true;
}
}
class Solution {
public boolean isAnagram(String s, String t) {
int n = s.length() , m = t.length();
if(n != m) return false;
int[] nums1 = new int[26];
for(int i = 0 ; i < s.length() ; i++){
int index = s.charAt(i)- 'a';
nums1[index]++;
}
for(int i = 0 ; i < t.length() ; i++){
int index = t.charAt(i)- 'a';
nums1[index]--;
if(nums1[index] < 0) return false;
}
return true;
}
}
class Solution {
public boolean containsDuplicate(int[] nums) {
Map<Integer,Integer> hash = new HashMap<>();
for(int i = 0 ; i < nums.length ; i++){
int e = nums[i];
hash.put(e,hash.getOrDefault(e,0)+1);
}
for(Map.Entry<Integer,Integer> hashMap : hash.entrySet()){
if(hashMap.getValue() > 1){
return true;
}
}
return false;
}
}
easy难度
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer , Integer> map = new HashMap<>();
for(int i = 0 ; i < nums.length ; i++){
int elem = nums[i];
if(map.get(elem) == null){
map.put(elem,i);
}else{
Integer cur = map.get(elem);
if(i - cur <= k){
return true;
}else{
map.put(elem,i);
}
}
}
return false;
}
}