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.youkuaiyun.com/wayne17/article/details/88355534