C/C++ 两数之和为目标值时返回下标

题目:给定一个整数数组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)
{
	// nums
	printf("\nnums = [");
	for (int i = 0; i < nums.size(); i++)
	{
		printf("%d%c", nums[i], (i==nums.size()-1)?(']'):(','));
	}

	// target
	printf("\ntarget = %d", target);

	// result
	printf("\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;
}

执行结果:

  • 16
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WendyWJGu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值