Leetcode 454 四数之和2
刷过很多遍了 哈希表的使用
回顾Java Map的用法
map.containsKey()
map.getOrDefault()
完整代码
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
int res = 0;
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < nums1.length; i++){
for(int j = 0; j < nums2.length; j++){
map.put((0 - nums1[i] - nums2[j]),
map.getOrDefault((0 - nums1[i] - nums2[j]),0) + 1);
}
}
for(int i =0; i < nums3.length; i++){
for(int j = 0; j < nums4.length; j++){
if(map.containsKey(nums3[i] + nums4[j])){
res += map.get(nums3[i] + nums4[j]);
}
}
}
return res;
}
}
简单题 哈希表的应用
熟悉Java map方法 可以获取到所有value值,value值可重复
Collection<> values = map.values();
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
Map<Character, Integer> map = new HashMap<>();
for(char c1 : ransomNote.toCharArray()){
map.put(c1, map.getOrDefault(c1, 0) + 1);
}
for(char c2 : magazine.toCharArray()){
if(map.containsKey(c2)){
map.put(c2, map.get(c2) - 1);
}
}
for(Integer i : map.values()){
if(i > 0){
return false;
}
}
return true;
}
}
也可以使用数组作为哈希表 因为这题单词有小写字母组成,可以设置一个长为26的数组作为哈希表
重点题 使用双指针
题目要求不重复 去重的逻辑
一般去重 都要对原数组进行排序
熟悉Java Arrays工具类的用法
Arrays.sort(nums); 进行排序
Arrays.asList(nums[i], nums[left], nums[right]) 返回一个ArrayList
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int left = 0;
int right = 0;
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0 ; i < nums.length; i++){
if(i > 0 && nums[i] == nums[i-1]){
continue;
}
left = i + 1;
right = nums.length - 1;
while(left < right){
int sum = nums[i] + nums[left] + nums[right];
if(sum > 0){
right--;
}else if(sum < 0){
left++;
}else{
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
while(right > left && nums[left] == nums[left + 1]){
left++;
}
while(right > left && nums[right] == nums[right - 1]){
right--;
}
left++;
right--;
}
}
}
return res;
}
}
难题 和三数之和类似
去重的逻辑等
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++){
if(i > 0 && nums[i] == nums[i-1]){
continue;
}
if(nums[i] > 0 && nums[i] > target){
break;
}
for(int j = i + 1; j < nums.length; j++){
if(j > i + 1 && nums[j] == nums[j-1]){
continue;
}
int left = j + 1;
int right = nums.length - 1;
while(right > left){
long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];
if(sum > target){
right--;
}else if(sum < target){
left++;
}else{
res.add(
Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
while(left < right && nums[left] == nums[left+1]){
left++;
}
while(left < right && nums[right] == nums[right-1]){
right--;
}
left++;
right--;
}
}
}
}
return res;
}
}