454.四数相加II
题目链接:454.四数相加II
思路:将两个数组元素之和及出现次数放入map,统计另外两个元素之和,在map中寻找是否存在两数相加为0的情况,同时记录次数。
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map<Integer,Integer> map = new HashMap<>();
int target = 0;
int count = 0;
for(int a : nums1){
for(int b : nums2){
target = a+b;
if(map.containsKey(target)){
map.put(target,map.get(target)+1);
}else{
map.put(target,1);
}
}
}
for(int c : nums3){
for(int d : nums4){
target = c+d;
if(map.containsKey(0-target)){
count += map.get(0-target);
}
}
}
return count;
}
}
83.赎金信
题目链接:83.赎金信
思路:采用哈希数组,遍历magazine后将各个元素出现次数存入record,遍历ransomNote将对应字符个数做减法操作,如果数组中存在负数,说明ransomNote字符串中存在magazine没有的字符。
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] record = new int[26];
int temp;
for(int i = 0;i <= magazine.length()-1;i++){
temp = magazine.charAt(i) - 'a';
record[temp]++;
}
for(int i = 0;i <= ransomNote.length()-1;i++){
temp = ransomNote.charAt(i) - 'a';
if(record[temp]>0){
record[temp]--;
}else{
return false;
}
}
return true;
}
}
15.三数之和
题目链接:https://leetcode.cn/problems/3sum/
思路:双指针法
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-1;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--;
}else if(sum < 0){
left++;
}else{
result.add(Arrays.asList(nums[i],nums[left],nums[right]));
while (right > left && nums[right] == nums[right - 1]) right--;
while (right > left && nums[left] == nums[left + 1]) left++;
right--;
left++;
}
}
}
return result;
}
}
18.四数之和
题目链接:18.四数之和
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for(int k=0;k<=nums.length-1;k++){
if(nums[k]>0&&nums[k]>target){
return result;
}
if( k > 0 && nums[k-1] == nums[k]){
continue;
}
for(int i=k+1;i<=nums.length-1;i++){
if(i>k+1 && nums[i-1] == nums[i]){
continue;
}
int left = i+1;
int right = nums.length-1;
while(right>left){
long sum = (long) nums[k] + nums[i] + nums[left] + nums[right];
if(sum > target){
right--;
}else if(sum < target){
left++;
}else{
result.add(Arrays.asList(nums[k],nums[i],nums[left],nums[right]));
while (right > left && nums[right] == nums[right - 1]) right--;
while (right > left && nums[left] == nums[left + 1]) left++;
left++;
right--;
}
}
}
}
return result;
}
}