918. 三数之和

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 
            

 

posted @ 2020-07-07 22:15  风不再来  阅读(157)  评论(0编辑  收藏  举报