[Leetcode] 1、Two sum(兩數之和)題解
阿新 • • 發佈:2019-01-10
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].
題目解析:這道題目給了我們一個整數陣列,接著給我們一個目標值,如果陣列中的兩個值相加得到目標值,那麼要求我們返回這兩個數值的索引值。假設每個目標值只有一種解決方案,同時也不能使用同一個數值兩次。
思路:1、可以使用暴力解,利用雙重迴圈來遍歷陣列去獲得結果陣列,因為雙重迴圈的時間複雜度為O(n^2),所以超時。
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { // vector<int> result; for(int i=0;i!=nums.size();i++) { for(int j=i+1;i!=nums.size();j++) { if(target==(nums[i]+nums[j])) return {i,j}; } } } };
2、有一種比較簡單的演算法, 就是利用c++中Map來查詢,先將陣列的數值與索引作為map中的鍵值對儲存起來,然後通過map已有的函式find()來查詢(target-nums.at(i))的差值。
這種方法是利用空間來換取時間,時間複雜度為O(n)。
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { std::map<int,int> vals; for(int i=0;i!=nums.size();++i){ vals.emplace(nums.at(i),i); } for(int i=0;i!=nums.size();++i) { const int numToFind=target-nums.at(i); auto iter=vals.find(numToFind); if(iter!=vals.end()&&i!=iter->second) { return {i,iter->second}; } } } };
3、與2是同樣的原理,只不過利用的是unoredered_map,是無序關聯容器,內部採用hash表結構,檢索速度更快。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hash;//無序關聯容器,內部採用hash表結構,擁有快速檢索的特性
vector<int> result;
for (int i = 0; i < nums.size(); i++) {
int numberToFind = target - nums[i];
//if numberToFind is found in map, return them
if (hash.find(numberToFind) != hash.end()) {
//+1 because indices are NOT zero based
result.push_back(hash[numberToFind] );
result.push_back(i );
return result;
}
//number was not found. Put it in the map.
hash[nums[i]] = i;
}
return result;
}
};