Leetcode 454 四数相加II
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
HashMap<Integer, Integer> map = new HashMap<>();
int temp;
int res = 0;
for (int i : nums1) {
for (int j : nums2) {
temp = i + j;
map.put(temp, map.getOrDefault(temp, 0) + 1);
}
}
for (int i : nums3) {
for (int j : nums4) {
temp = i + j;
if (map.containsKey(0 - temp)) {
res += map.get(0 - temp);
}
}
}
return res;
}
}
Leetcode 383 赎金信
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] arr = new int[26];
int temp;
for (int i = 0; i < magazine.length(); i++) {
temp = magazine.charAt(i) - 'a';
arr[temp]++;
}
for (int i = 0; i < ransomNote.length(); i++) {
temp = ransomNote.charAt(i) - 'a';
if (arr[temp] > 0) {
arr[temp]--;
} else {
return false;
}
}
return true;
}
}
Leetcode 15 三数之和
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
if(nums == null || nums.length < 3) {
return list;
}
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2; i++) {
if(i > 0 && nums[i] == nums[i-1]) {
continue;
}
int target = -nums[i];
int j = i + 1;
int k = nums.length - 1;
while(j < k) {
int sum = nums[j] + nums[k];
if(sum == target) {
List<Integer> cur = new ArrayList<>();
cur.add(nums[i]);
cur.add(nums[j]);
cur.add(nums[k]);
list.add(cur);
j++;
while(j < k && nums[j] == nums[j-1]) {
j++;
}
k--;
while(j < k && nums[k] == nums[k+1]) {
k--;
}
} else if(sum > target) {
k--;
} else {
j++;
}
}
}
return list;
}
}
Leetcode 18 四数之和
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
if(nums.length < 4) {
return res;
}
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2; i++) {
if(i > 0 && nums[i] == nums[i-1]) {
continue;
}
for(int j = nums.length - 1; j > 2; j--) {
if(j < nums.length - 1 && nums[j] == nums[j+1]) {
continue;
}
int m = i + 1;
int n = j - 1;
while(m < n) {
double sum = (double)nums[i] + (double)nums[j] + (double)nums[m] + (double)nums[n];
if(sum < Integer.MIN_VALUE || sum > Integer.MAX_VALUE) {
return res;
}
if((int)sum == target) {
List<Integer> cur = new ArrayList<>();
cur.add(nums[i]);
cur.add(nums[j]);
cur.add(nums[m]);
cur.add(nums[n]);
res.add(cur);
m++;
while(m < n && nums[m] == nums[m-1]) {
m++;
}
n--;
while(m < n && nums[n] == nums[n+1]) {
n--;
}
} else if(sum > target) {
n--;
} else {
m++;
}
}
}
}
return res;
}
}