leetcode 每日一题 18. 四数之和

双指针法

思路:

参考三数之和,在外面多嵌套一层

代码:

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        if len(nums) < 4:
            return []
        output = []
        nums.sort()
        for i in range(len(nums)-3):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            for j in range(i+1,len(nums)-2):
                if j >i+1 and nums[j] == nums[j-1]:
                    continue
                L = j+1
                R = len(nums)-1
                while L<R:
                    if nums[i]+nums[j]+nums[L]+nums[R] == target:
                        output.append([nums[i],nums[j],nums[L],nums[R]])
                        while L<R and nums[L+1] == nums[L]:
                            L += 1
                        while L<R and nums[R-1] == nums[R]:
                            R -= 1
                        L +=1
                        R -=1
                    elif nums[i]+nums[j]+nums[L]+nums[R] < target:
                        L +=1
                    else:
                        R -=1
        return output

猜你喜欢

转载自www.cnblogs.com/nilhxzcode/p/12808053.html