链接:代码随想录
文章目录
- 454.四数相加II
- 383.赎金信
- 15.三数之和
- 18.四数之和
- 解题方法
- 题目思路
- 示例代码
- 总结
解题思路
1.454.四数相加II 解题思路
对map中的key,value的直接运用,解法可以将4个式子边成2个式子简化过程
代码如下(示例):
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map<Integer,Integer> map = new HashMap<>();
int temp;
int res = 0;
for(int i: nums1){
for(int j: nums2){ //同时遍历
temp = i+j;
if(map.containsKey(temp)){
map.put(temp,map.get(temp)+1); //出现相同的,对应次数加1
}else{
map.put(temp,1);
}
}
}
for(int i: nums3){
for(int j: nums4){
temp = i + j;
if(map.containsKey(0-temp)){
res+=map.get(0-temp); //记录个数
}
}
}
return res;
}
}
2.383.赎金信 解题思路
判断出现字母的重复次数,用数组作为哈希表更简便
代码如下(示例):
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] record = new int[26];
for(char c: magazine.toCharArray()){ //重复次数记录
record[c - 'a']+=1;
}
for(char c: ransomNote.toCharArray()){ //重复之后次数减一
record[c - 'a']-=1;
}
for(int i: record){
if(i < 0){
return false;
}
}
return true;
}
}
3.15.三数之和 解题思路
双指针 时间复杂度o(n^2)
代码如下(示例):
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; //如果都为正数那一定无法为0
}
if(i > 0 && nums[i] == nums[i-1]){ //去重
continue;
}
int left = i+1;
int right = nums.length - 1;
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(right > left && nums[right] == nums[right-1]) right--; //去重
while(right > left && nums[left] == nums[left+1]) left++;
right--;
left++;
}
}
}
return result;
}
}
4.18.四数之和 解题思路
双指针 时间复杂度o(n^3)
代码如下(示例):
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++) {
// nums[i] > target 直接返回, 剪枝操作
if (nums[i] > 0 && nums[i] > target) {
return result;
}
if (i > 0 && nums[i - 1] == nums[i]) {
continue;
}
for (int j = i + 1; j < nums.length; j++) {
if (j > i + 1 && nums[j - 1] == nums[j]) {
continue;
}
int left = j + 1;
int right = nums.length - 1;
while (right > left) {
long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];
if (sum > target) {
right--;
} else if (sum < target) {
left++;
} else {
result.add(Arrays.asList(nums[i], nums[j], 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;
}
}
总结
通常题型能用数组的即可用数组,因为哈希值空间占用大,特别分散,容易造成空间资源浪费,而一旦数组所以的限制无法满足,则可以采用set 来实现哈希表,而map作为<key value>形式上可以访问下标,面对此类18.15.问题则map是首选,最后是双指针的熟练运用可以有效减少时间复杂度。