两数之和

牛客题霸 两数之和 C++题解/答案

题目描述
给出一个整数数组,请在数组中找出两个加起来等于目标值的数,
你给出的函数twoSum 需要返回这两个数字的下标(index1,index2),需要满足 index1 小于index2.。注意:下标是从1开始的
假设给出的数组中只存在唯一解
例如:
给出的数组为 {20, 70, 110, 150},目标值为90
输出 index1=1, index2=2

示例1
输入
复制
[3,2,4],6
返回值
复制
[2,3]

题目:
水题。。
直接两个for循环暴力走起
两个for循环看哪两个数之和等于目标值
然后用num俩记录坐标

题解:
class Solution { public:
/**
*
* @param numbers int整型vector
* @param target int整型
* @return int整型vector
*/
vector twoSum(vector& numbers, int target) { // write code here
vectornum; for(int i=0;i<numbers.size();i++) { for(int j=i+1;j<numbers.size();j++) { if(numbers[i]+numbers[j]==target) { num.push_back(i+1); num.push_back(j+1); } } } return num; } };

posted @ 2020-12-02 23:41  回归梦想  阅读(176)  评论(0编辑  收藏  举报