硕士毕业,找工作面试,被狠狠的鄙视了,所以痛定思痛,将LeetCode从第一题开始刷,刷到哪算哪:
1.题目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
列子:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1];
题目很简单:给定一个int数组和一个目标值,返回数组中两个数之和等于目标值的这两个数的索引。
2. 解法
2.1穷举法
这是首先想到的方法,也是最简单直接的方法。
遍历所有两个数之和,找到等于目标值的两个数即可。
代码如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
using namespace std;
vector<int> result{};
for(int i = 0; i < sizeof(nums);i++)
{
for(int j = i + 1;j < sizeof(nums);j++)
{
if(nums[i] + nums[j] == target)
{
result.push_back(0);
result.push_back(1);
break;
}
}
}
return result;
}
};
此题用到了 vector;
vector是C++标准模板库中的部分内容,它是一个多功能的,能够操作多种数据结构和算法的模板类和函数库。vector之所以被认为是一个容器,是因为它能够像容器一样存放各种类型的对象,简单地说,
vector是一个能够存放任意类型的动态数组,能够增加和压缩数据。