15算法课程 167. Two Sum II
来源:互联网 发布:网站备案域名查询 编辑:程序博客网 时间:2024/06/05 04:46
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
solution:
可以假设每个输入的目标值都只有一个解决方案,并且不能使用相同的元素相加两次。
code:
class Solution {public: vector<int> twoSum(vector<int>& numbers, int target) { vector<int> ans; int ending = numbers.size() - 1; int temp; for(int i = 0; i <= ending; ++i){ int toFound = target - numbers[i]; int temp = search(numbers, i+1, ending, toFound); if(temp != -1){ ans.push_back(i+1); ans.push_back(temp+1); break; } } return ans; } int search(vector<int> &n, int low, int high, int target){ while(low <= high){ int mid = (low + high) / 2; if(n[mid] == target){ return mid; } else if(n[mid] > target) high = mid - 1; else low = mid + 1; } return -1; }};
阅读全文
0 0
- 15算法课程 167. Two Sum II
- 15算法课程 1. Two Sum
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- java 类
- 阿里云 CDN HTTPS 最佳实践——动态密钥套件(三)
- ORA-01861: 文字与格式字符串不匹配,ORA-01722: 无效数字
- HDU
- ubuntu16.04+cuda8.0的安装
- 15算法课程 167. Two Sum II
- ceph-deploy的set_overrides函数
- 自动化测试框架: KIF和EarlGrey对比
- linux sql导出xls,导出Excel,导出表格,表格乱码(中文解决)
- 关流
- CentOS7上运行Rancher的潜在问题之devicemapper
- smart_ptr
- linux的文件系统
- Python 3.6 类的特殊方法一