題目難度: Easy
原題描述:
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].
題目大意:
給你一個包含n個數的數組和一個目標值,要你返回數組中和等於目標值的兩個數的下標。本題假設每個輸入都有一個唯一的解,而且結果的兩個數不能是同一個元素。
解題思路:
對於數組中的每一個元素,使用map記錄該元素對應的下標,即map的key爲元素的值,value爲元素的下標。記錄的同時在map中查找key爲(target-該元素的值)的元素是否存在,若存在且與原先的不是同一個元素,則返回這兩個元素的下標;否則,則繼續執行下一次循環。
時間複雜度分析:
由於使用了C++中的map,因此每次在在map中進行查找操作的複雜度爲O(log(n)),總的複雜度爲O(n*log(n))。而如果使用C++中的hash_map,則每次查找的複雜度爲O(1),總的複雜度爲O(n),但是由於LeetCode不支持C++的hash_map(自己加上#include <hash_map>也沒有用),因此只能用map來做了。網上看見有人用C++11的unordered_map來做,時間複雜度也能去到O(n),其內部也是用哈希表來實現,也是很不錯的方法。
以下是代碼:
vector<int> twoSum(vector<int>& nums, int target)
{
int i;
map<int, int> m;
map<int, int>::iterator p;
vector<int> result;
for(i=0 ; i<nums.size() ; ++i)
{
p = m.find(target-nums[i]);
if(p!=m.end() && p->second!=i)
{
result.push_back(i);
result.push_back(m[target-nums[i]]);
}
m[nums[i]] = i;
}
if(result[0]>result[1])
swap(result[0],result[1]);
return result;
}