leetcode: Two Sum
阿新 • • 發佈:2018-12-13
感受到了自己與大神的差距,同樣的題,我的程式碼跑140ms,大神的只要4ms。
題目:
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].
我的程式碼(暴力遍歷):
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { int first=-1,second=-1; for(int i=0;i<nums.size();++i){ //if(nums[i]<target){ for(int j=0;j<i;++j){ if(i!=j && nums[i]+nums[j]==target){ if(i>j){ first=j;second=i; } if(i<j){ first=i;second=j; } } // } } } return vector<int>{first,second}; } };
時間複雜度O(n²) 思路:兩層迴圈,每兩個都配對嘗試一遍,忽略掉index相同的部分。
大神的程式碼(One-pass Hash Table):
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> map; for (int i = 0; i < nums.size(); i++) { int complement = target - nums[i]; if (map.find(complement) != map.end() && map[complement] != i) { return vector<int> {map[complement], i}; } map.emplace(nums[i], i); } } };
時間複雜度O(n) 思路:建立一個hashTable,每次將資料放入前檢查hashTable中是否已有當前要放入數的補數。
測試程式:
#include<iostream>
#include<vector>
#include<map>
#include<unordered_map>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
unordered_map<int, int> map;
for (int i = 0; i < nums.size(); i++)
{
int complement = target - nums[i];
if (map.find(complement) != map.end() && map[complement] != i)
{
return vector<int> {map[complement], i};
}
map.emplace(nums[i], i);
}
}
};
//判斷是否合格的巨集
#define REQUIRE(sol) {\
if(sol)\
cout<<"passed"<<endl;\
else cout<<"not passed"<<endl;\
}
int main(){
Solution s;
//測試集
std::vector<int> v1{2, 7, 11, 15};
REQUIRE( (s.twoSum(v1, 9) == std::vector<int>{0, 1}) );
std::vector<int> v2{0, 4, 3, 0};
REQUIRE( (s.twoSum(v2, 0) == std::vector<int>{0, 3}) );
std::vector<int> v3{-3, 4, 3, 90};
REQUIRE( (s.twoSum(v3, 0) == std::vector<int>{0, 2}) );
std::vector<int> v4{2, 15, 11, 7};
REQUIRE( (s.twoSum(v4, 9) == std::vector<int>{0, 3}) );
return 0;
}
炫一下自己的提交:
Time Submitted Status Runtime Language 13 hours, 14 minutes ago [**Accepted**](https://leetcode.com/submissions/detail/177511062/) 4 ms cpp 13 hours, 15 minutes ago [**Accepted**](https://leetcode.com/submissions/detail/177511034/) 8 ms cpp 13 hours, 17 minutes ago [**Accepted**](https://leetcode.com/submissions/detail/177510934/) 8 ms cpp 13 hours, 34 minutes ago [**Accepted**](https://leetcode.com/submissions/detail/177509923/) 12 ms cpp 14 hours, 6 minutes ago [**Accepted**](https://leetcode.com/submissions/detail/177508255/) 4 ms cpp 14 hours, 31 minutes ago [**Accepted**](https://leetcode.com/submissions/detail/177506900/) 324 ms cpp 18 hours, 5 minutes ago [**Accepted**](https://leetcode.com/submissions/detail/177485296/) 140 ms cpp 324ms那個是自己寫了一個根據value查詢key的函式,結果效率奇底。12ms那個是用的map,沒有使用unordered_map,所以慢了點。