[Leetcode]Two Sum
2013-10-17 10:16
603 查看
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
思路:使用一个struct保留排序前的下标号,然后设置两个下标index1,index2依次从前往后,从后往前
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
思路:使用一个struct保留排序前的下标号,然后设置两个下标index1,index2依次从前往后,从后往前
class Solution { public: struct node{ int val; int index; }; bool compare(const node& a, const node& b){ return a.val < b.val; } vector<int> twoSum(vector<int> &numbers, int target) { vector<int> result; int index1 = 0; int index2 = 0; vector<node> resu_node; node temp; for(int i = 0;i < numbers.size();i++) { temp.index = i + 1; temp.val = numbers[i]; resu_node.push_back(temp); } sort(resu_node.begin(),resu_node.end(),compare); for(int i = 0,j = resu_node.size() - 1; i < j;) { if(resu_node[i].val + resu_node[j].val == target){ index1 = resu_node[i].index; index2 = resu_node[j].index; result.push_back(index1); result.push_back(index2); break; }else if(resu_node[i].val + resu_node[j].val > target){ j--; }else{ i++; } } return result; } };
相关文章推荐
- WEB打印
- .NET MV4 Remote远程验证注意事项及案例
- 关于JAVA项目中CLASSPATH路径详解
- 在html中添加javascript脚本<script>的方法和应注意的事项
- Excel 多表切换假死
- 2.4 Picking Values with UIPickerView
- xPool - 基于mysqlclient的mysql的c++连接池 - xnhcx的个人空间 - 开源中国社区
- Visual Studio各版本区别
- 《dive into python3》 笔记摘录
- 转载的log4cplus使用指南
- Excel 多表切换假死
- java 枚举类的简单介绍及使用枚举类的内部类编写的星期几的小案例
- jQuery.Validate 验证
- mysql 常用命令
- 查询连接数
- 音响常用的电解电容
- 智能指针
- mtrace检查内存泄漏
- 使用外键让两张表级联删除更新
- Move模式的细化