网站开发费入什么费用,东莞seo建站排名,秦皇岛视频优化代理,百度热搜广告位题目#xff1a;给定一个整数数组nums和一个整数目标值target#xff0c;在该数组中找出和为目标值target的那两个整数#xff0c;并返回它们的数组下标。 前提假设#xff1a;每种输入只会对应一个答案。但是#xff0c;数组中同一个元素在答案里不能重复出现。可以按任意…题目给定一个整数数组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;vectorint TwoSum(vectorint nums, int target)
{int pos1 0;int pos2 0;for (pos1 0; pos1nums.size() - 1; pos1){for (int pos2 pos1 1; pos2nums.size(); pos2){if (nums[pos1] nums[pos2] target){return{ pos1, pos2 };}}}return{ pos1, pos2 };
}void PrintStr(vectorint nums, int target, vectorint result)
{// numsprintf(\nnums [);for (int i 0; i nums.size(); i){printf(%d%c, nums[i], (inums.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[])
{vectorint nums { 2, 7, 11, 15 };int target 9 ;vectorint 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;
}
执行结果