哈希表的应用
目录
1. 两数之和
【题目】:
【代码】:
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<nums.length; i++){
map.put(nums[i],i);
}
for(int i=0; i<nums.length; i++){
int temp=target-nums[i];
if(map.containsKey(temp) && map.get(temp)!=i){
return new int[] {i, map.get(temp)};
}
}
throw new RuntimeException("error");
}
或者
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> indexForNum = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (indexForNum.containsKey(target - nums[i])) {
return new int[]{indexForNum.get(target - nums[i]), i};
} else {
indexForNum.put(nums[i], i);
}
}
return null;
}
217. 存在重复元素
【题目】:
【代码】:
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set=new HashSet<>();
for(int i=0; i<nums.length; i++){
if(set.add(nums[i])==false){
return true;
}
}
return false;
}
}
594. 最长和谐子序列
【题目】:
【代码】:
public int findLHS(int[] nums) {
Map<Integer,Integer> map=new HashMap<>();
for(int i=0; i<nums.length; i++){
map.put(nums[i],map.getOrDefault(nums[i], 0)+1);
}
int max=0;
for(int key: map.keySet()){
if(map.containsKey(key+1)){
max=Math.max(max,map.get(key)+map.get(key+1));
}
}
return max;
}
另外:
这三道题执行时间都不是特别好,仅提供一种思路