版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35508033/article/details/89020009
两数之和
https://leetcode-cn.com/problems/two-sum/description/
//这题不难,只需要熟悉hashmap即可
//在hashmap里面,key是差,value是index。比如例子中的[2,7,11,15],target是9
//那么在2的时候就存入7 0,下一位找到7的时候,之前有个差值是7,那么就返回7对应的index,0,以及当前这个7的index,就是1了
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result=new int[2];
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
int cur=nums[i];
int toFind=target-cur;
if(map.containsKey(cur)){
result[0]=map.get(cur);
result[1]=i;
}else{
map.put(toFind,i);
}
}
return result;
}
}
三数之和
https://leetcode-cn.com/problems/3sum/description/
//这题用脚后跟看都是2Sum的follow up
//就是在一个数组里面挑3个数字,这三个数字的和为0就行
//A+B是2Sum,A+B+C是3Sum,那么稍加修改A+(B+C)就成了这两道题连接的桥梁。所以这题的基本思路就是套了个壳子而已
//值得一提的是,此题可能有重复数字,而且要求不能有重复结果,所以使用双指针法
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++){
int cur=nums[i];
//重复的数字跳过
if(i>0&&nums[i]==nums[i-1]){
continue;
}
int left=i+1,right=nums.length-1;
while(left<right){
int two_sum=nums[left]+nums[right];
if(two_sum+cur>0){
right--;//大了就往左边移动
}else if(two_sum+cur<0){
left++;//小了就右移动
}else{
List<Integer> list=new ArrayList<Integer>();
list.add(nums[left]);
list.add(nums[right]);
list.add(cur);
result.add(list);
//跳过重复的数字
while(left+1<=right&&nums[left]==nums[left+1]){
left++;
}
while(right-1>=left&&nums[right]==nums[right-1]){
right--;
}
left++;
right--;
}
}
}
return result;
}
}
四数之和
https://leetcode-cn.com/problems/4sum/description/
//这次是4个,就是找四个数,它们的和是目标数
//这次就是3Sum套了个壳而已,方法都是一样的
//这次是4个,就是找四个数,它们的和是目标数
//这次就是3Sum套了个壳而已,方法都是一样的
public 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-3; i++){
if(i > 0 && nums[i] == nums[i-1]){//去掉重复的数字
continue;
}
for(int j = i+1; j < nums.length-2; j++){
if(j > i+1 && nums[j] == nums[j-1]) {//同样是去掉重复数字
continue;
}
int low = j+1, high = nums.length-1;
while(low < high){
int sum = nums[i] + nums[j] + nums[low] + nums[high];
if(sum == target){
res.add(Arrays.asList(nums[i],nums[j], nums[low], nums[high]));//这里新建一个list也行
//重复的数字跳过
while(low+1 < high && nums[low+1] == nums[low]){
low++;
}
while(high-1 > low && nums[high-1] == nums[high]){
high--;
}
low++;
high--;
}else if(sum < target){
low++;
}else{
high--;
}
}
}
}
return res;
}
}