首页 > 其他 > 详细

918. 三数之和

时间:2020-07-07 22:37:10      阅读:61      评论:0      收藏:0      [点我收藏+]

918. 三数之和

中文English

给定一个n个整数的数组和一个目标整数target,找到下标为i、j、k的数组元素0 <= i < j < k < n,满足条件nums[i] + nums[j] + nums[k] < target.

样例

样例1

输入: nums = [-2,0,1,3], target = 2
输出: 2
解释:
因为有两种三个元素之和,它们的和小于2:
[-2, 0, 1]
[-2, 0, 3]

样例2

输入: nums = [-2,0,-1,3], target = 2
输出: 3
解释:
因为有三种三个元素之和,它们的和小于2:
[-2, 0, 1]
[-2, 0, 3]
[-2, -1, 3]

挑战

你可以用时间复杂度为O(n^2)的算法解决这个题吗?

 
 
输入测试数据 (每行一个参数)如何理解测试数据?

 三指针(一个固定 + 背向型双指针) + 排序

class Solution:
    """
    @param nums:  an array of n integers
    @param target: a target
    @return: the number of index triplets satisfy the condition nums[i] + nums[j] + nums[k] < target
    """
    def threeSumSmaller(self, nums, target):
        # Write your code here
        if not nums: return 0 
        
        res = 0
        length = len(nums)
        
        nums = sorted(nums)
        
        #三个指针,背向型双指针,不管怎么变,第一个肯定是不同的
        for i in range(length - 2):
            #在中间进行取区间
            left, right = i + 1, length - 1 
            
            while left < right:
                #如果是小于的话,则符合,继续往右边走,否则的话,right - 1,缩小区间,维持小于target状态
                if (nums[i] + nums[left] + nums[right] < target):
                    print(i, left, right)
                    res += right - left
                    left += 1 
                else:
                    right -= 1 
                    
        return res 
            

 

918. 三数之和

原文:https://www.cnblogs.com/yunxintryyoubest/p/13263650.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!