[leetcode]18. 四数之和

LEETCODE15:三数之和
LEETCODE16:最接近的三数之和

1.题目:
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

2.代码:
1.遍历+三数之和:

/**
 * Return an array of arrays of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int compare(const void* a, const void* b) {
    return (*(int*)a)-(*(int*)b);
}

int** fourSum(int* nums, int numsSize, int target, int* returnSize) {
    *returnSize=0;
    int** r=malloc(sizeof(int*)*numsSize*numsSize);
    qsort(nums,numsSize,sizeof(int),compare);
    //四数之和
    for(int k=0;k<numsSize-3;k++){
    	//去重,取重复段的第一个,不然输入[0,0,0,0],0直接结束
        if(k>0&&nums[k]==nums[k-1])            
                continue;        
        //三数之和
        int newtarget=target-nums[k];       
        for(int i=k+1;i<numsSize-2;i++){ 
            //去重,i==k+1时即第一个不管,取重复段的第一个          
            if(i>k+1&&nums[i]==nums[i-1])
                continue;          
            //二数之和
            int newtarget2=newtarget-nums[i];
            int m=i+1;
            int n=numsSize-1;                        
            while(m<n){                      
                if(nums[m]+nums[n]>newtarget2)
                    n--;
                else if(nums[m]+nums[n]<newtarget2)
                    m++;
                else{                         
                    int *s=(int *)malloc(sizeof(int )*4);       
                    s[0]=nums[k];
                    s[1]=nums[i];
                    s[2]=nums[m++];
                    s[3]=nums[n--];
                    r[*returnSize]=s;
                    (*returnSize)++;      
                    //去重,取各自前进方向上第一个
                    while(m<numsSize-1&&nums[m]==nums[m-1])
                        m++;
                    while(n>i+1&&nums[n]==nums[n+1])                
                        n--;               
                }                                   
            }
        }   
    }
    return r;
}

⇒ 进阶,加上剪枝:

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        result = []
        if not nums or len(nums) < 4:
            return []
        nums.sort()
        length = len(nums)
        #定义4个指针k,i,j,h  k从0开始遍历,i从k+1开始遍历,留下j和h,j指向i+1,h指向数组最大值
        for k in range(length - 3):
            # 当k的值与前面的值相等时忽略
            if k > 0 and nums[k] == nums[k - 1]:
                continue
            # 获取当前最小值,如果最小值比目标值大,说明后面越来越大的值根本没戏
            min1 = nums[k] + nums[k+1] + nums[k+2] + nums[k+3]
            if min1 > target:
                break
            # 获取当前最大值,如果最大值比目标值小,说明后面越来越小的值根本没戏,忽略
            max1 = nums[k] + nums [length-1] + nums[length - 2] + nums[length - 3]
            if max1 < target:
                continue
            for i in range(k+1, length-2):
                if i > k + 1 and nums[i] == nums[i - 1]:
                    continue
                j = i + 1
                h = length - 1
                min2 = nums[k] + nums[i] + nums[j] + nums[j + 1]
                if min2 > target:
                    continue
                max2 = nums[k] + nums[i] + nums[h] + nums[h - 1]
                if max2 < target:
                    continue
                # 开始j指针和h指针的表演,计算当前和,如果等于目标值,j++并去重,h--并去重,当当前和大于目标值时h--,当当前和小于目标值时j++
                # 只有当找到了target才要去重
                while j < h:
                    curr = nums[k] + nums[i] + nums[j] + nums[h]
                    if curr == target:
                        result.append([nums[k], nums[i], nums[j], nums[h]])
                        j += 1
                        while j < h and nums[j] == nums[j - 1]:
                            j += 1
                        h -= 1
                        while j < h and i < h and nums[h] == nums[h + 1]:
                            h -= 1
                    elif curr > target:
                        h -= 1
                    elif curr < target:
                        j += 1

        return result

2.按情况进行分类(不推荐):

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        if len(nums)<4:
            return []
        r = []
        counter = collections.Counter(nums)
        counts = dict(counter)
        # counts = {}
        # for i in nums:
        #     counts[i] = counts.get(i, 0) + 1
        nums = sorted(counts)
        lens = len(nums)
        for i in range(lens):
            num = nums[i]
            #4,0
            t = target
            if counts[num] >= 4 and t%4 == 0 and num == t//4:
                r.append([t//4,t//4,t//4,t//4])
            #3,1
            t = target-3*num
            if counts[num] >= 3 and t>num:
                if t in nums:
                    r.append([num,num,num,t])
            #2,2
            t = target -2*num
            if counts[num] >= 2 and t%2 == 0 and t//2 in counts and counts[t//2]>=2 and t//2>num:
                r.append([num,num,t//2,t//2])
            #2,1,1
            t = target -2*num
            if counts[num] >= 2:                
                m,n = i+1,lens-1
                while m<n:
                    if nums[m]+nums[n]>t:
                        n = n-1
                    elif nums[m]+nums[n]<t:
                        m = m+1
                    else:
                        r.append([num,num,nums[m],nums[n]])
                        m = m+1
                        n = n-1
            #1,...
            t = target-num
            for j in range(i+1,lens):
                if counts[nums[j]]>1:
                    # 3,0
                    if t%3==0 and nums[j]==t//3 and counts[t//3]>2:
                        r.append([num,nums[j],nums[j],nums[j]])
                    # 2,1
                    elif t-2*nums[j] in nums and t-2*nums[j]!=nums[j] and t-2*nums[j]>num:
                        r.append([num,nums[j],nums[j],t-2*nums[j]])
                # if t-nums[j]>nums[j]:
                m,n = j+1,lens-1
                while m<n:
                    if nums[m]+nums[n]>t-nums[j]:
                        n = n-1
                    elif nums[m]+nums[n]<t-nums[j]:
                        m = m+1
                    else:
                        r.append([num,nums[j],nums[m],nums[n]])
                        n = n-1
                        m = m+1   
        return r

3.知识点:

二数之和->三数之和->四数之和->N数之和

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值