题目
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.
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
分析
这道题乍一看,一点也不难,不就是遍历两遍就好了,但是坑有两个:
- 不能重复利用数组中同样的元素
刚开始写你可能不会注意,遍历起来i=0, j=0就会踩到这样的坑,j = i 也会! - 每种输入只对应一个答案
你也不能 j = i ,这样你就重复的用了两遍了元素,j = i+1就错开了
暴力求解
class Solution {
public:
vector<int> result={
};
vector<int> twoSum(vector<int>& nums, int target) {
for (int i=0;i< nums.size();i++)
for (int j = i+1; j < nums.size(); j++)
{