题目链接:454. 四数相加 II - 力扣(LeetCode)
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0 || nums3 == null || nums3.length == 0 || nums4 == null || nums4.length == 0){
return 0;
}
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int count = 0;
for(int i = 0; i < nums1.length; i ++){
for(int j = 0; j < nums2.length; j ++){
int temp = nums1[i] + nums2[j];
if(map.containsKey(temp)){
int frequency = map.get(temp);
map.put(temp, ++frequency);
continue;
}
map.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(map.containsKey(temp)){
count += map.get(temp);
}
}
}
return count;
}
}
两两组合
lass Solution {
public boolean canConstruct(String ransomNote, String magazine) {
if(magazine.length() < ransomNote.length()){
return false;
}
int[] arr = new int[26];
for(char i: magazine.toCharArray()){
arr[i - 'a'] ++;
}
for(char i: ransomNote.toCharArray()){
arr[i - 'a'] --;
}
for(int i: arr){
if(i < 0){
return false;
}
}
return true;
}
}
集合或者自制哈希,集合开销时间反而更大
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++){
if(nums[i] > 0){
return result;
}
if(i > 0 && nums[i] == nums[i-1]){
continue;
}
int left = i + 1;
int right = nums.length - 1;
while(right > left){
int sum = nums[i] + nums[left] + nums[right];
if(sum > 0){
right --;
}
if(sum < 0){
left ++;
}
if(sum == 0){
result.add(Arrays.asList(nums[i], 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 result;
}
}
数组排序,去重
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length; i ++){
if(nums[i] > 0 && nums[i] > target){
return result;
}
if(i > 0 && nums[i] == nums[i - 1]){
continue;
}
for(int j = i + 1; j < nums.length; j ++){
if(nums[i] > 0 && (nums[i] + nums[j]) > target){
return result;
}
if(j > i + 1 && nums[j] == nums[j - 1]){
continue;
}
int left = j + 1;
int right = nums.length - 1;
while(left < right){
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if(sum > target){
right --;
}
if(sum < target){
left ++;
}
if(sum == target){
result.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 result;
}
}
在三数之和上又多了层循环