1.求数组中两数之和为目的值
Two Sums
针对给定的数组序列是无序的
class Solution {
public int[] twoSum(int[] nums, int target) {
//对于无序数组的两数之和
HashMap<Integer,Integer> hm = new HashMap<>();
for(int i = 0;i < nums.length;i++){
int k = target - nums[i];
if(hm.containsKey(k)){
return new int[]{i,hm.get(k)};
}
hm.put(nums[i],i);
}
return new int[]{-1,-1};
}
}
2.判断数组中是否存在重复元素
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a48bed81a09dc8e23631b311b4d30cf7.png)
3.求满足特定条件序列的长度
class Solution {
public int findLHS(int[] nums) {
HashMap<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;
}
}
4.求最长连续序列的长度
思路:使用HashMap,时间复杂度是O(N)
class Solution {
public int longestConsecutive(int[] nums) {
HashSet<Integer> set = new HashSet<>();
int max = 0;
for(int i = 0;i < nums.length;i++){
set.add(nums[i]);
}
for(int key:set){
if(!set.contains(key-1)){
int tmp = 1;
while(set.contains(key+1)){
tmp++;
key++;
}
max = Math.max(tmp,max);
}
}
return max;
}
}