Day7哈希表进阶
基础知识
HashMap的使用总结
1.创建
Map<Integer,Integer> num = new HashMap<>();
2.查询是否存在key
if(num.containsKey(temp)){ ··· }
3.获取键的值
value = map.get(key);
4.设置值(更新操作相同)
num.put(key,value);
题目
梳理
本题目不用去重,所以还是相对简单。思路大体为:
-
将这些数组两两组队
-
数组一和数组二的分别值的和以(值,次数)的形式存入hashmap
-
看-1*(数组三和数组四分别的和)在不在在hashmap里面
本题因为是全小写字母,因此可以用哈希地址策略
本题一开始想的是用暴力去解,但是超时了,得用双指针,此种解法的时间复杂度在o(n^2)以内
本题是在三数之和的基础上套了一层循环,思路是一样的;但是需要剪纸,不然会有溢出的情况
代码
454
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
int count = 0;
Map<Integer,Integer> num = new HashMap<>();
for(int i = 0;i < nums1.length ; i++){
for(int j = 0;j<nums2.length;j++){
int temp = nums1[i] + nums2[j];
if(num.containsKey(temp)){
num.put(temp,num.get(temp)+1);
}else{
num.put(temp,1);
}
}
}
for(int i = 0;i < nums3.length ; i++){
for(int j = 0;j<nums4.length;j++){
int temp =0 - nums3[i] - nums4[j];
if(num.containsKey(temp)){
count += num.get(temp);
}
}
}
return count;
}
}
383
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int []record = new int [27];
for(char c:magazine.toCharArray()){
record[c - 'a']++;
}
for(char c:ransomNote.toCharArray()){
record[c - 'a']--;
}
for(int i = 0;i<26;i++){
if(record[i]<0)
return false;
}
return true;
}
}
15
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> set = new HashSet<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
int left = i + 1;
int right = nums.length - 1;
while (left<right){
// System.out.println("i:"+i+" left:"+left+" right:"+right);
// System.out.println("num[i]:"+nums[i]+" num[left]:"+nums[left]+" num[right]:"+nums[right]);
// System.out.println("-----");
//刚好相等
if(nums[i]+nums[left]+nums[right] == 0){
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[left]);
temp.add(nums[right]);
temp.sort(Comparator.naturalOrder());
left++;right--;
set.add(temp);
}else if(nums[i]+nums[left]+nums[right]<0){
left++;
}else {
right--;
}
}
}
return new ArrayList<>(set);
}
}
18
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Set<List<Integer>> set = new HashSet<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length - 1; j++) {
if (nums[i] > 0 && nums[i] > target) {
return new ArrayList<>(set);
}
int left = j + 1;
int right = nums.length - 1;
while (left < right){
int temp = nums[i] + nums[j] + nums[left] + nums[right];
if(temp == target){
List<Integer> tmp = new ArrayList<>();
tmp.add(nums[i]);
tmp.add(nums[j]);
tmp.add(nums[left]);
tmp.add(nums[right]);
tmp.sort(Comparator.naturalOrder());
set.add(tmp);
left++;right--;
}else if(temp < target){
left++;
}else {
right --;
}
}
}
}
return new ArrayList<>(set);
}
}