Leetcode1:Two Sum(两数之和)

Description:

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,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

Example

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution 1: Brute Force(暴力)

#include <iostream>
#include <vector>

using namespace std;

vector<int> twoSum(vector<int>& nums, int target)
{
	vector<int> a;

	for (int i = 0; i < nums.size(); i++)
		for (int j = i + 1; j < nums.size(); j++)
		{
			if (nums[i] + nums[j] == target)
			{
				a.push_back(i);
				a.push_back(j);
			}
		}

	return a;
}

int main(void)
{
	vector<int> a = {4, 5, 8, 6};
	int target = 11;
	vector<int> arr = twoSum(a, target);
	
	for (vector<int>::size_type i = 0; i != arr.size(); i++)
		cout << arr[i] << " ";

	cout << endl;
}

结果:…
泪目。。。
也难怪,毕竟 时间复杂度是 O ( n 2 ) O(n^2) O(n2).

C 暴力
#include <stdio.h>
#include <stdlib.h>
int* twoSum(int* nums, int numsSize, int target)
{
	int *a;
	a = (int*)malloc(2 * sizeof(int));
	for (int i = 0; i < numsSize; i++)
	{
		for (int j = i + 1; j < numsSize; j++)
		{
			if (nums[i] + nums[j] == target)
			{
				a[0] = i;
				a[1] = j;
				//printf("%d %d\n", i, j); // 自己验证一下
				break;
			}
		}
	}
	return a;
}

int main(void)
{
	int b[] = {4, 5, 9, 1, 7};
	twoSum(b, 5, 12);

	return 0;
}

在这里插入图片描述

Solution 2:Hash Table(哈希表)

#include <iostream>
#include <vector>
#include <map>

using namespace std;

vector<int> twoSum(vector<int>& nums, int target)
{
	vector<int> a;
	vector<int>::iterator i;
	map<int, int> Map;  //map<key, value>

	for (vector<int>::size_type i = 0; i != nums.size(); i++)   // 先将数组存入表中,数组元素作 key,索引作 value
		Map[nums[i]] = i;

	for (vector<int>::size_type t = 0; t != nums.size(); t++)
	{
		int res = target - nums[t];
		if (Map.find(res) != Map.end() && Map.find(res)->second != t)
		{   // map.find()只能根据 key 值查找,若找到,返回所在位置的迭代器,否则返回 map.end()
			a.push_back(t);
			a.push_back(Map.find(res)->second);
			break;
		}
	}

	return a;
}


int main(void)
{
	vector<int> a = {4, 5, 6, 8, 1};
	twoSum(a, 13);

	return 0;
}

第一次用C++的 map 容器,第一次用哈希表。。
在这里插入图片描述
哈希表,不愧是以空间换时间?,时间复杂度 O ( n ) O(n) O(n)

C++ map详细用法:https://blog.csdn.net/wayne17/article/details/88355534

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值