Two Sum
2015-07-07 23:04
267 查看
Given an array of integers, 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
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
class Solution { public: template <typename T> vector<size_t> sort_indexes(vector<T> &v) { // initialize original index locations vector<size_t> idx(v.size()); for (size_t i = 0; i != idx.size(); ++i) idx[i] = i; // sort indexes based on comparing values in v sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) {return v[i1] < v[i2];}); sort(v.begin(), v.end()); return idx; } int select(vector<int>& nums, int start, int end, int value) { if(start > end) return -1; if(nums[(start + end)/2] == value) return (start + end)/2; else if(nums[(start + end)/2] < value) { start = (start + end)/2 + 1; select(nums, start, end, value); } else{ end = (start + end)/2 -1; select(nums, start, end, value); } } vector<int> twoSum(vector<int>& nums, int target) { //sorted nums ascendingly. vector<size_t> sorted_indexes = sort_indexes(nums); int result; vector<int> two_sum; for(int i = 0; i < nums.size(); i++) { //look for number = target-nums[i] int index = select(nums, i+1, nums.size() - 1, target-nums[i]); if(index != -1) { int a1 = 0; int a2 = 0; if(sorted_indexes[i] < sorted_indexes[index]){ a1 = sorted_indexes[i]+1; a2 = sorted_indexes[index] + 1; } else{ a1 = sorted_indexes[index] + 1; a2 = sorted_indexes[i]+1; } two_sum.push_back(a1); two_sum.push_back(a2); return two_sum; } } return two_sum; } };
相关文章推荐
- 2015070710 - 晚11早4作息
- 数据仓库之ETL漫谈
- 树莓派入手,相关设置以及使用迅雷远程下载
- 每天一个linux命令(11):nl命令
- 回调机制详解
- centos7 创建桌面快捷方式(chrome,eclipse)
- kettle连接hadoop&hdfs图文详解
- CSS基础 - 页面布局
- 深入java单例模式(转)
- android sqlite 数据类型
- 2015-7-4
- udp服务端和客户端程序示例
- 2015070709 - 挑战更换
- 【android Studio】零git知识、零脚本命令,即刻体验git版本管理魅力!
- shell中${}的妙用
- poj1573 模拟
- linux中描述符和标准IO流对文件的基本操作
- Spring学习(15)--- 基于Java类的配置Bean 之 @Bean & @Scope 注解
- hdu 2571 命运
- js的数组ECMAScript 5加入的方法(二)