zoukankan      html  css  js  c++  java
  • Two Sum II

    Given an array of integers, find how many pairs in the array such that their sum is bigger than a specific target number. Please return the number of pairs.

    Given numbers = [2, 7, 11, 15], target = 24. Return 1. (11 + 15 is the only pair)

    这是Lintcode上的一道题目,可以算是Two Sum 的follow up,求两数之和超过一定值的对数。既然是超过一定的值,不是一个定值,hashmap是没法使用的,这个时候排序和two pointer就要出马了。

    首先对数组进行排序。然后初始化left = 0, right = n-1。如果nums[right] + nums[left] > target, 则[i,right] (left =< i < right)的所有组合都符合条件,此时right在当前位置的作用已经失去了,所以right--。反之,如果nums[right] + nums[left] <= target, 说明这个left不合格,不能找到另一数字和其匹配,left++。代码如下:

    class Solution:
        # @param nums, an array of integer
        # @param target, an integer
        # @return an integer
        def twoSum2(self, nums, target):
            if not nums or len(nums) < 2:
                return 0
            nums.sort()
            left = 0
            right = len(nums) - 1
            res = 0
            while left < right:
                if nums[left] + nums[right] <= target:
                    left += 1
                else:
                    res += right - left 
                    right -= 1
            
            return res

    这种解法的时间复杂度为O(nlogn) + O(n) = O(nlogn), 空间复杂度为O(1)(就地排序的话)。

  • 相关阅读:
    通过jsonp解决ajax的跨域请求问题
    为php安装redis扩展模块并测试
    浅谈使用 PHP 进行手机 APP 开发(API 接口开发)(转)
    touch事件记录
    jquery mobile 问题
    background总结,转自http://www.daqianduan.com/3302.html
    博客收集
    css3 border-radius 总结
    css3 box-shadow 总结
    angular 重置表单
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5563878.html
Copyright © 2011-2022 走看看