LeetCode:Two Sum
問題の説明:
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:
code:
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:
code:
//leetcode
//tony 2014.9.25
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int index = 0;
int index1 = 0;
int index2 = 0;
vector<int> nums1(nums);
sort(nums1.begin(),nums1.end()); //
vector<int>::size_type length = nums1.size();
cout<<length<<endl;
for(vector<int>::size_type ix = 0,is = --length;is != ix;)
{
index = nums1[ix] + nums1[is];
if(index == target)
{
index1 = ++ix;
index2 = ++is;
}
else if(index < target)
{
++ix;
}
else
{
--is;
}
}
cout<<"index1 = "<<index1<<","<<"index2 = "<<index2<<endl;
vector<int>::size_type index3 = 0;
vector<int>::size_type index4 = 0;
for(vector<int>::size_type ix = 0; ix != length; ++ix )
{
if(nums[ix] == index1)
index3 = ++ix;
if(nums[ix] == index2)
index4 = ++ix;
}
cout<<"index3 = "<<index3<<","<<"index4 = "<<index4<<endl;
}
};