167. Two Sum II - Input array is sorted
来源:互联网 发布:语音通话交友软件 编辑:程序博客网 时间:2024/05/26 05:53
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
从i开始枚举,然后从i+1至.size()-1二分查找,好笨的方法=。=
#include <iostream>#include <vector>#include <set>#include <algorithm>#include <cmath>using namespace std;class Solution {public: vector<int> twoSum(vector<int>& numbers, int target) { vector<int>vec; for (vector<int>::size_type i = 0; i < numbers.size(); ++i) { left = i + 1; right = numbers.size() - 1; int result = BinarySearch(numbers, target - numbers[i]); if (numbers[i] + numbers[result] == target) { //cout << numbers[i] << " " << numbers[result] << endl; vec.push_back(i + 1); vec.push_back(result + 1); break; } } return vec; }private:int left;int right;int mid;#define max(a,b) (((a) > (b)) ? (a) : (b))#define min(a,b) (((a) > (b)) ? (b) : (a))int BinarySearch(vector<int>& numbers, int target){while(left <= right) { mid = (left + right) / 2; if(numbers[mid] > target) { right = mid - 1; } else if(numbers[mid] < target) { left = mid + 1; } else { return mid; } } return right;}};int main(){ Solution s; vector<int>vec{1,2,3,4,4,9,56,90}; vector<int>v = s.twoSum(vec, 8); for (vector<int>::size_type i = 0; i < v.size(); ++i) { cout << v[i] << endl; }return 0;}
15 / 15 test cases passed.
Status: Accepted
Runtime: 13 ms
Submitted: 2 minutes ago
0 0
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Leetcode-167.Two Sum II - Input array is sorted
- [leetcode] 167. Two Sum II - Input array is sorted
- 【leetcode】167. Two Sum II - Input array is sorted
- 【LeetCode】167. Two Sum II - Input array is sorted
- 167. Two Sum II - Input array is sorted
- 167. Two Sum II - Input array is sorted
- 167. Two Sum II - Input array is sorted
- [LeetCode OJ]167. Two Sum II - Input array is sorted
- [leetcode]167. Two Sum II - Input array is sorted
- 167. Two Sum II - Input array is sorted
- 共享内存总结以及实现代码
- Java NIO Scatter / Gather
- 高精度进制转换 poj 1220 NUMBER BASE CONVERSION
- aspx.cs中使用windows.open打开另一个页面,实现参数传递
- 趣谈字符集
- 167. Two Sum II - Input array is sorted
- Linux进程通信 有名管道实现守护进程
- HDU2187
- 主机无法用ssh连接虚拟机问题
- 关于xshell无法连接虚拟机上的centos问题
- Powerdesigner jdbc链接mysql失败问题(逆向工程)
- python自动化运维学习-系统性能模块详解
- Linux目录结构
- JDBC连接mysql数据库