Two Sum II
来源:互联网 发布:我知女人心南宫寒txt 编辑:程序博客网 时间:2024/06/07 05:12
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 and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
class Solution {public: vector<int> twoSum(vector<int>& numbers, int target) { vector<int> ans; int n = numbers.size(); for(int i=0; i<=n/2; i++) { int tmp = target - numbers[i]; int id = lower_bound(numbers.begin(), numbers.end(), tmp) - numbers.begin(); if(id < n && numbers[i] + numbers[id] == target) { if(id == i) id++; ans.push_back(i+1); ans.push_back(id+1); return ans; } } return ans; }};
阅读全文
0 0
- [leetcode] Two Sum II
- Two Sum II
- #443 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
- jsp 文件上传与下载
- 重构类
- android 简单的自定义UI(以Button为例)
- 重新组织数据
- KNN
- Two Sum II
- 搭建zabbix监控windows
- Themes of Eclipse --玩转Eclipse
- Android Service完全解析(上)
- 关注民生民情——华北水利水电大学“情艺”薛岗社区调查
- Android反编译
- PEP 8 —Python代码风格指南(一)
- USB鼠标驱动简单设计
- tensorflow1.1/autoencoder2