两数之和
此题有两种方法可以求解。
1.普通方法
最简单的方法就是两重for循环暴力求解。
//leetcode-1
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length - 1; i++){
for(int j = i + 1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
return new int[]{i, j};
}
}
}
return null;
}
}
2.进阶方法
使用HashMap可以降低其时间复杂度,Key存储值,Value存储下标,只进行一趟循环,每次判断target - nums[i]是否存在于map中,如果存在则直接返回两下标值,不存在就将当前点存入map中。
//leetcode-1
class Solution {
public int[] twoSum(int[] nums, int target) {
Map map = new HashMap();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(target - nums[i])){
return new int[]{i, (int) map.get(target - nums[i])};
}
map.put(nums[i], i);
}
return null;
}
}
四数相加
题目中给出了四个数组,将其分为两组,两个为一组,前两组将数组元素之和存到HashMap中,Key为数组之和,Value为此和出现的次数。然后在后两组数组中循环,判断(0-后两数组元素之和)是否存在于map中,并将其对应出现次数加入到结果中。
//leetcode-454
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map map = new HashMap();
int count = 0;
for(int i : nums1){
for(int j : nums2){
int key = i + j;
int value = (int) map.getOrDefault(key,0) + 1;
map.put(key, value);
}
}
for(int i : nums3){
for(int j : nums4){
if(map.containsKey(0 - i - j)){
count += (int) map.get(0 - i - j);
}
}
}
return count;
}
}
未完待续。。。