leetcode 454 四数相加
public static int fourSumCount(int[] A,int[] B,int[] C,int[]D){
int result =0;//最终结果
HashMap<Integer,Integer> hashMapAB = new HashMap<>();
int cnt=0;
int sumAB=0;
for(int i=0;i<A.length;i++){
for (int j = 0; j < B.length; j++) {
sumAB = A[i]+B[j];
if(hashMapAB.containsKey(sumAB)){
cnt = hashMapAB.get(sumAB);
cnt++;
hashMapAB.put(sumAB,cnt);
}else {
hashMapAB.put(sumAB,1);
}
}
}
int sumCD=0;
for(int i=0;i<C.length;i++){
for (int j = 0; j < D.length; j++) {
sumCD = C[i]+D[j];
if(hashMapAB.containsKey((0-sumCD))) {
result += hashMapAB.get((0-sumCD));
}
}
}
return result;
}
leetcode 383 赎金信
跟异位词逻辑差不多
public static boolean canConstruct(String ransomNote,String magazine){
if(ransomNote.length()> magazine.length()) return false;
int[] arr = new int[26];
//长度固定,利用了数组
for (char c:ransomNote.toCharArray()) {
arr[c-'a']++;
}
for (char c:magazine.toCharArray()) {
arr[c-'a']--;
}
for (char c:ransomNote.toCharArray()) {
if(arr[c-'a']!=0) return false;
}
return true;
}
leetcode 015 两数之和
去重不要忘
public static List<List<Integer>> threeSum(int[] nums){
ArrayList<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);// 先排序
if (nums[0] > 0) return new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
int left = i + 1;
int right = nums.length - 1;// 两个指针是关键,提升了效率, O(n3) 降为 O(n2)
if (i > 0 && nums[i] == nums[i - 1]) continue;
while (left < right) {
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 (left<right && nums[left] == nums[left + 1]) left++;
while (left< right && nums[right] == nums[right - 1]) right--;
right--;
left++;
}
}
}
return result;
}
leetcode 018 四数之和
public static List<List<Integer>> fourSum(int[] nums, int target){
ArrayList<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
int left=0;
int right=0;
long sum =0;
for(int i=0;i<nums.length;i++){
if(i>0 && nums[i]==nums[i-1]) continue;
for(int j=i+1;j<nums.length;j++) {
left = j+1;
right = nums.length - 1;
while (left < right) {
// long !和会超过int 长度
sum= (long) nums[i] + nums[j] + nums[left] + nums[right];
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
while(j<right&& nums[j]==nums[j+1]) j++;
while(left<right&& nums[left]==nums[left+1]) left++;
while(left<right&& nums[right]==nums[right-1]) right--;
left++;
right--;
}
}
}
}
return result;
}