[LintCode][Two Pointers] Two Sum II.md

Problem

More Discussions

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.

Example

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

Challenge

Do it in O(1) extra space and O(nlogn) time.

Solution

Two Pointers的思想,先排序数组。如果a[i] + a[j] > target, 说明 a[i..j]之间的数的和都大于target所以只要累加j-i个数就行了,之后j--,继续寻找。

class Solution {
public:
    /**
     * @param nums: an array of integer
     * @param target: an integer
     * @return: an integer
     */
    int twoSum2(vector<int> &nums, int target) {
        // Write your code here
        sort(nums.begin(), nums.end());
        int i = 0;
        int j = nums.size() - 1;
        int count = 0;
        while (i < j) {
            int sum = nums[i] + nums[j];
            if (sum > target) {
                count += j - i;
                j--;
            } else {
                i++;
            }
        }
        
        return count;
    }
};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,774评论 0 33
  • 我的小屋修好了 它是我最珍贵的所有。 我的小屋修好了 虽然它可能还很不牢固。 ——但我把小屋修好了。 我很 开心。...
    Conn一只舟阅读 176评论 0 1
  • -1- 三寸金莲 早上出门买驴肉火烧的时候,碰到一位同来店里买火烧的老太太.老太太两鬓斑白,拄着拐杖一步步慢悠悠的...
    试图思考的二哥阅读 1,101评论 12 4
  • 不知说些什么,一如既往的空虚,不过不能再让自己堕落啦!开学啦,新学期,开启新的征程。站在原地,只能停止成长的脚步。
    墨桃阅读 109评论 0 0
  • 写给张爱玲 文||与你相识 今天是你远去的日子 那些才情和故事 谁还放在心头 能否明白在最好的日子遇见最好的你 你...
    与你相识_40fa阅读 440评论 2 6