#443 Two Sum II
来源:互联网 发布:阿里云主机大学生 编辑:程序博客网 时间:2024/05/21 14:01
题目描述:
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.
把array从小到大进行sort,再用两个pointers:l指向array的头,r指向array的尾。当nums[l] + nums[r]的值满足条件时,这也表示l = l...r - 1和r的组合也满足条件,这时可以skip这一段的检查,下一个loop中r = r - 1;当他俩的值不满足条件时,这也表示r = l + 1...r和l的组合也不满足条件,这样也可以skip相应的情况。
Mycode(AC = 66ms):
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 l = 0, r = nums.size() - 1; int num_pairs = 0; while (l < r) { // if sum > target, then // sum of l = l...r-1 and r = r // all > target if (nums[l] + nums[r] > target) { num_pairs += r - l; r--; } // if sum <= target, then // don't need to consider r = l + 1...r else { l++; } } return num_pairs; }};
0 0
- #443 Two Sum II
- [leetcode] Two Sum II
- Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- LeetCode : Two Sum II
- Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- leetcode_167 Two Sum II
- 167. Two Sum II
- LeetCode167.Two Sum II
- leetcode167~Two Sum II
- 167. Two Sum II
- Java 面试题
- iOS 之 cocoapods安装与使用
- 字符串反转
- 学习之路~sqh
- 二叉树遍历算法的应用
- #443 Two Sum II
- 设计模式学习第十一天
- Android帧率测试
- 用RotateDrawable实现网易云音乐唱片机效果
- bfs加传送机问题
- 基于UML的需求分析和系统设计
- jeecg中下拉框增加没有的属性dictSelect
- 数学公式是如何实现的?
- BC#86.1003(HDOJ5806)NanoApe Loves Sequence Ⅱ