题目:给定一个整数数组nums和一个整数目标值target,在该数组中找出和为目标值target的那两个整数,并返回它们的数组下标。
前提假设:每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
示例 4:
输入:nums = [-1,-2,-3,-4,-5], target = -8
输出:[2,4]
解析: 使用嵌套循环加和比对
示例源码:
// len12.cpp : 定义控制台应用程序的入口点。
//#include "stdafx.h"
#include <string>
#include <algorithm>
#include <vector>
using namespace std;vector<int> TwoSum(vector<int>& nums, int target)
{int pos1 = 0;int pos2 = 0;for (pos1 = 0; pos1<nums.size() - 1; pos1++){for (int pos2 = pos1 + 1; pos2<nums.size(); pos2++){if (nums[pos1] + nums[pos2] == target){return{ pos1, pos2 };}}}return{ pos1, pos2 };
}void PrintStr(vector<int>& nums, int target, vector<int>& result)
{// numsprintf("\nnums = [");for (int i = 0; i < nums.size(); i++){printf("%d%c", nums[i], (i==nums.size()-1)?(']'):(','));}// targetprintf("\ntarget = %d", target);// resultprintf("\nresult = [");for (int i = 0; i < result.size(); i++){printf("%d%c", result[i], (i == result.size() - 1) ? (']') : (','));}printf("\n" );}int _tmain(int argc, _TCHAR* argv[])
{vector<int> nums = { 2, 7, 11, 15 };int target =9 ;vector<int> result = TwoSum(nums, target);PrintStr(nums, target, result);nums = { 3, 2, 4 };target = 6;result = TwoSum(nums, target);PrintStr(nums, target, result);nums = { 3, 3 };target = 6;result = TwoSum(nums, target);PrintStr(nums, target, result);nums = { -1, -2, -3, -4, -5 };target = -8;result = TwoSum(nums, target);PrintStr(nums, target, result);return 0;
}
执行结果: