首页 » 技术分享 » leecode(1)Two Sum

leecode(1)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

anser

#include <stdio.h>   
#include <iostream>
#include  <vector>
using namespace std;
// const int numCount=20;
// int numArray[numCount]={1,23,123,2,45,35,64,75,7,33,21,77,8,2,72,345,3245,55,28,34};
int index1=0,index2=0;
void twosum(std::vector<int> &nums,int target){
if (nums.size()<1)
{
return;
/* code */
}
  for (int i = 0; i < nums.size()-1; ++i)
  {
for (int j =i+1; j <  nums.size(); ++j){
if(nums[i]+nums[j]==target){
index1=i;
        index2=j;
}
/* code */
}
}
/* code */
}

int  main()
{
std::vector<int> vNum;
vNum.push_back(12);
vNum.push_back(7);
vNum.push_back(76);
vNum.push_back(34);
vNum.push_back(22);
vNum.push_back(14);
vNum.push_back(18);
twosum(vNum,21);
if (index2!=0)
{
cout<<"index1= "<<index1<<" ,index2= "<<index2;
/* code */
}
else{
cout<<"not exist!!!";
}

/* code */
return 0;
}

有直接使用库函数的,还不如自己编写一个。

就是两个循环。

转载自原文链接, 如需删除请联系管理员。

原文链接:leecode(1)Two Sum,转载请注明来源!

0