【LeetCode】Two Sum
2014-04-15 21:57
330 查看
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
思路:排序,从最两头开始加。
struct Node { int nu, po; }; bool cmp(Node a, Node b) { return a.nu < b.nu; } class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> index_back; vector<Node> num; index_back.clear(); int nsize=numbers.size(),i,j,k; if(nsize<2)return index_back; for(i=0;i<nsize;i++){ Node temp; temp.nu=numbers[i]; temp.po=i; num.push_back(temp); } sort(num.begin(),num.end(),cmp); j=0; k=nsize-1; for(;j<k;){ if(j>0&&num[j].nu==num[j-1].nu){ j++; continue; } if(k<num.size()-1&& num[k].nu==num[k+1].nu){ k--; continue; } if(num[j].nu+num[k].nu>target)k--; else if(num[j].nu+num[k].nu<target)j++; else { if(num[j].po>num[k].po){ index_back.push_back(num[k].po+1); index_back.push_back(num[j].po+1); }else{ index_back.push_back(num[j].po+1); index_back.push_back(num[k].po+1); } return index_back; } } return index_back; } };
相关文章推荐
- LeetCode之Two Sum
- [LeetCode] Two Sum
- leetcode1~Two Sum
- LeetCode Two Sum
- leetcode:Two Sum
- leetcode 1: 找出两个数相加等于给定数 two sum
- leetcode: two sum
- leetcode--Two Sum
- LeetCode 学习笔记:Question 1、Two Sum
- 【leetcode系列】Two Sum
- LeetCode题解——Two Sum
- leetcode-two sum
- [leetcode, python] Two Sum 两数之和等于某数
- Leetcode-1:Two Sum
- LeetCode 151 Two Sum
- LeetCode 1. Two Sum
- LeetCode1-Two Sum
- Leetcode-01 two sum
- leetcode 1 Two Sum
- [LeetCode]Two Sum