1 问题:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].译: 给出一个整数数组, 找出其中两个数相加等于target的 对应下标。 假设数组肯定存在两个元素满足相加等于target的条件,并且这两个元素 下标不一样。
2 方法:
方法一: 时间复杂度O(n^2). 差评。 [ me ]
#include<stdio.h>
#include<stdlib.h>
int* twoSum(int* nums, int numsSize, int target);
int main()
{
int a[4] = {2,5,7,12};
int numSize = 4;
int target = 9;
int *result = twoSum(a, numSize, target);
if(NULL != result)
{
printf("a:%d\n", result[0]);
printf("b:%d\n", result[1]);
free(result);
}
return 0;
}
/**
* * Note: The returned array must be malloced, assume caller calls free().
* */
int* twoSum(int* nums, int numsSize, int target) {
if (NULL == nums)
{
printf("no 1");
return NULL;
}
int* result = (int *)malloc(sizeof(int)*2);
if (NULL == result)
{
printf("no 2");
return NULL;
}
int i=0, j = 0;
for(;i < numsSize; i++)
for(j=i+1; j< numsSize; j++)
{
printf("%d,%d\n", nums[i], nums[j]);
if (target == nums[i] + nums[j])
{
result[0] = i;
result[1] = j;
return result;
}
}
return NULL;
}
方法二:时间复杂度O(n), 好评。
vector<int> twoSum(vector<int> &numbers, int target)
{
//Key is the number and value is its index in the vector.
unordered_map<int, int> hash;
vector<int> result;
for (int i = 0; i < numbers.size(); i++)
{
int numberToFind = target - numbers[i];
//if numberToFind is found in map, return them
if (hash.find(numberToFind) != hash.end())
{
result.push_back(hash[numberToFind]);
result.push_back(i);
return result;
}
//number was not found. Put it in the map.
hash[numbers[i]] = i;
}
return result;
}
3. unordered_map的find方法:
Return value
An iterator to the element, if the specified key value is found, or unordered_map::end if the specified key is not found in the container.Member types iterator and const_iterator are forward iterator types.
Example
| |
4. 延伸:
关于 unordered_map,又叫hash_map,实际是“hashtable” 【与redis 的字典结构一样】。 如图:
详情见: http://blog.csdn.net/blues1021/article/details/45054159