zoukankan      html  css  js  c++  java
  • 【python-leetcode259-双指针】三个数的最小和

    问题描述:

    Example:
    
    Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.
    
    For example, given nums = [-2, 0, 1, 3], and target = 2.
    
    Return 2. Because there are two triplets which sums are less than 2:
    
    [-2, 0, 1] [-2, 0, 3]
    
    Follow up: Could you solve it in O(n2) runtime?

    大致意思是给定一个数组和一个目标值,求出所有三个数的和小于目标值的总数。

    解题:

    class Solution(object):
        def threeSumSmaller(self, nums: List[int], target: int) -> int:    
            #如果nums为空或者长度小于3,直接返回0
            if not nums and len(nums) < 3:
                return 0
            #先排序    
            nums.sort()
            #如果前三个数的和都大于或等于target,直接返回0
            if nums[0]+nums[1]+nums[2]>=target:
                return 0
            #保存结果
            res = 0
            #从左到右依次遍历
            for i in range(0, len(nums)):
                #左指针和右指针
                l, r = i + 1, len(nums) - 1
                #循环条件,核心就是下标为i的数为核心
                #逐渐增大左指针指向的值,减小右指针指向的值,以匹配所有情况
                while l < r:
                    #如果当前三个值和小于target,此时说明以i,l~r之间组成都可以,比如[-2,0,1,3],target=2
                    #[-2,0,3]是可行的,那么左指针不变,右指针一直左移,这时都是符合条件的
                    if nums[i] + nums[l] + nums[r] < target:
                        res += r - l
                        #再让左指针右移,判断下一种情况
                        l += 1
                    else:
                        #如果当前三个数值大于或等于target,需要让右指针左移使值变小些
                        r -= 1
        return res

    输入:[-2,0,1,3]   输出:2

    是一道会员题,提交不了。

  • 相关阅读:
    [Protractor] Test Simple Binding With Protractor
    [Angular 2] A Simple Form in Angular 2
    [ES6] Converting an array-like object into an Array with Array.from()
    [Falcor] Intro to JSON Graph
    [Angular + Webpack] ocLazyLoad compoment
    [Falcor] Retrieving Multiple Values
    [MongoDB] Introduce to MongoDB
    [Protractor] Getting Started With Protractor
    [AngularJS] Use ng-model-options to limit $digest
    ylbtech-协议-网络-安全协议:HTTPS
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12323545.html
Copyright © 2011-2022 走看看