leetcode twoSum
阿新 • • 發佈:2018-11-19
1.暴力搜尋時間複雜度O(n^2)
#include<iostream> #include<vector> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> ret; for(int i=0;i<nums.size(); i++) { for(int j=i+1; j<nums.size(); j++) { if(nums[i]+nums[j]==target) { ret.push_back(i); ret.push_back(j); return ret; } } } return ret; } };
注意:
- vector
- nums.size() 可以返回nums的大小。
- ret.push_back(i) 向ret裡面儲存值。
利用雜湊,時間複雜度O(n)
#include<iostream> #include<vector> #include<unordered_map> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> v(2, 0); // val+id unordered_map<int, int> hash; // we can search num and insert it to hash map at same time // and current num must be not in hash map for (int i = nums.size(); i--; hash[nums[i]] = i) { if (hash.find(target - nums[i]) == hash.end()) // 將nums與序號聯絡起來,直到能找到一對為止 continue; v[0] = i; // the index from 0 to n-1 v[1] = hash[target - nums[i]]; // 查詢 return v; } return v; // no answer return {0,0} } };
注意:
- vector
- unorder_map find的時間複雜度O(1), unorder_map.find 如果key存在,則find返回key對應的迭代器,如果key不存在,則find返回unordered_map::end。
- continue 停止執行後面語句,重新開始迴圈