python两数和的目标_给个数组,找出其中四个数使得其之和为给定的一个目标值,用python...

展开全部

class Solution(object):

def fourSum(self, nums, target):

"""

:type nums: List[int]

:type target: int

:rtype: List[List[int]]

"""

length = len(nums);

result = [];

nums.sort(); #先排序

first = 0;

while first < length - 3: #第一个数最右的位置也只能到32313133353236313431303231363533e4b893e5b19e31333363373133倒数第四

second = first + 1;

while second < length - 2: #第二个数最右的位置也只能到倒数第三

third = second + 1;

fourth = length - 1;

sum12 = nums[first] + nums[second];

while third < fourth:

sum = sum12 + nums[third] + nums[fourth];

error = target - sum;

if error == 0: #如果四个数之和刚好等于目标值,加入结果list

result.append([nums[first],nums[second],nums[third],nums[fourth]]);

while third < length - 1 and nums[third] == nums[third + 1]:

third += 1;

third += 1; #将第三个数的索引移动下一个不一样的数上去

while second < length - 1 and nums[second] == nums[second + 1]:

second += 1; #将第二个数的索引移动到最后一个一样的数上

while first < length - 1 and nums[first] == nums[first + 1]:

first += 1; #将第一个数的索引移动到最后一个一样的数上

elif error > 0: #当四个数之和小于目标值,第三个数的索引右移到一个不同的数上

while third < length - 1 and nums[third] == nums[third + 1]:

third += 1;

third += 1;

else: #当四个数之和大于目标值,第四个数的索引左移到一个不同的数上

while fourth > 0 and nums[fourth] == nums[fourth - 1]:

fourth -= 1;

fourth -=1;

second += 1;

first += 1;

return result;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值