题目_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.
给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。
要求:这个函数twoSum必须要返回能够相加等于目标数字的两个数的索引,且index1必须要小于index2。请注意一点,你返回的结果(包括index1和index2)都不是基于0开始的,即自1开始
你可以假设每一个输入肯定只有一个结果。
我的代码(C++实现),笨笨的遍历:
#include<iostream>
using namespace std;
int main()
{
const int size = 10;
int numlist[size];
int tem_storge;
int sum_target;
int sum_temp;
int first;
int second;
//--------------------------------------------------------------------------------------------------------------
//数组录入
std::cout << "请输入"<<size<<"个整数作为数组元素" << endl;
cout << " 数组大小为:" << size << endl;
for (int i = 0;i < size ;i++)
{
cout << "第" << i + 1 << "个元素是: ";
cin >> tem_storge;
cin.get();
cout << endl;
numlist [ i ] = tem_storge;
}
cout << "数组录入完毕\n";
cout << "数组数据为:\n";
for (int i = 0; i < size ; i++)
{
cout << "数组第" << i + 1 << "个元素为: " << numlist[i] << endl;
}
cout << "输出完毕\n";
cout << endl;
//-----------------------------------------------------------------------------------------------------------------------
//寻找相加和为特定值的两个元素
cout << "请输入目标和" << endl;
cin >> sum_target;
cin.get();
// 最笨的遍历
//bug 重复显示
for (int first = 0; first< size; first++)
{
for (second = first+1; second < size;second++)
{
sum_temp = numlist[first] + numlist[second];
if (sum_temp == sum_target)
{
if (first != second)
{
cout << "MATCH SUSSCESS! " << endl;
cout << "第" << first + 1 << "个元素:" << numlist[first] << " & 第" << second + 1 << "个元素: " << numlist[second] << "相加的和为" << sum_target << endl;
}
}
//else cout << "没有找到这两个元素";
}
}
cout << "程序结束!!" << endl;
cin.get();
return 0;
}
输出结果为:
请输入10个整数作为数组元素
数组大小为:10
第1个元素是: 1
第2个元素是: 3
第3个元素是: 5
第4个元素是: 7
第5个元素是: 9
第6个元素是: 11
第7个元素是: 13
第8个元素是: 15
第9个元素是: 17
第10个元素是: 21
数组录入完毕
数组数据为:
数组第1个元素为: 1
数组第2个元素为: 3
数组第3个元素为: 5
数组第4个元素为: 7
数组第5个元素为: 9
数组第6个元素为: 11
数组第7个元素为: 13
数组第8个元素为: 15
数组第9个元素为: 17
数组第10个元素为: 21
输出完毕
请输入目标和
20
MATCH SUSSCESS!
第2个元素:3 & 第9个元素: 17相加的和为20
MATCH SUSSCESS!
第3个元素:5 & 第8个元素: 15相加的和为20
MATCH SUSSCESS!
第4个元素:7 & 第7个元素: 13相加的和为20
MATCH SUSSCESS!
第5个元素:9 & 第6个元素: 11相加的和为20
程序结束!!
较为优秀的代码:
思考:
改进
待更新。。。