【Leetcode】Two Sum
来源:互联网 发布:qq空间域名申请 编辑:程序博客网 时间:2024/05/29 17:05
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
水题,要注意的是,当找到两个值后需要寻找下标时,给其中一个值设置标志位,当找到这个值后无需继续寻找这个值。然后就是需要将找到的结果排序输出。
class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> result; if(numbers.empty()) return result; vector<int> backup(numbers); sort(numbers.begin(),numbers.end()); getIndex(result,numbers,target); int index1,index2; bool finding=true; for(int i=0;i<backup.size();i++) { if(backup[i]==result[0]&&finding) { index1=i+1; finding=false; continue; } if(backup[i]==result[1]) index2=i+1; } result.clear(); result.push_back(index1); result.push_back(index2); sort(result.begin(),result.end()); return result; } void getIndex(vector<int> &result,vector<int> &numbers,int target) { for(int i=numbers.size()-1;i>=0;i--) { if(target>numbers[i]) { int index2=numbers[i]; bool index1=find(numbers,target-numbers[i],0,i-1); if(index1) { result.push_back(target-index2); result.push_back(index2); return; } else continue; } } } bool find(vector<int> &numbers,int target,int start,int end) { if(end<start) return false; int medium=(start+end)>>1; if(target==numbers[medium]) return true; else if(target<numbers[medium]) return find(numbers,target,start,medium-1); else return find(numbers,target,medium+1,end); } };
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- ios开发(十四)view之间的切换
- Java程序调用kettle中的job及trans
- 虚拟机设置桥接网卡
- 并查集的树实现
- ov5640,ov9712
- 【Leetcode】Two Sum
- Linux 中如何查询和卸载已安装的软件
- 整形数值与字符型数值大小比较
- cocos2dx之利用CCSpriteBatchNode创建多个Sprite
- android下的点击事件的4种形式
- log4j日志封装说明—slf4j对于log4j的日志封装-正确获取调用堆栈
- nyoj 176 整数划分(二)
- 蓝桥杯 C++ 输入一个自然数n,n的立方等于n 个连续的奇数和
- java程序中给Kettle传参数