1.两数之和

题目:

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum

思路:

一.所用变量:(1)用result来保存结果

                 (2)用 i, j 来代表下标

            (3)用标志变量found来标记是否找到

二.i 从 0 开始,到倒数第二个位置结束(因为两个数字为一组, 所以没必要到数组最后一个), j 从 i 的后一个位置开始,到数组末尾结束(因为元素不重复选取),

再设置一个标志变量标记结果,找到了就立即退出循环。

代码:

#include <iostream>
#include <vector>
using namespace std;

class solution {
public:
vector<int> get_index(vector<int> num, int target) {
int i, j;
int len = num.size();
vector<int> result;
bool found = false;

for (i = 0; i < len - 1 && !found; ++i) {
for (j = i + 1; j < len; ++j) {
if (num[i] + num[j] == target) {
result.push_back(i);
result.push_back(j);
found = true;
break;
}
}
}

return result;
}
};

int main()
{
vector<int> num { 2, 7, 11, 15 };
int target = 9;
solution s1;

vector<int> result = s1.get_index(num, target);

cout << "[" << result[0] << "," << result[1] << "]";

return 0;
}


原文地址:https://www.cnblogs.com/Hello-Nolan/p/12085029.html