leetcode-algorithms-1 two sum
阿新 • • 發佈:2018-11-14
leetcode-algorithms-1 two sum
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
直接對陣列進行兩個迴圈匹配,相等返回.
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> t; for (int one = 0; one < nums.size() - 1; ++one) { for (int two = one + 1; two < nums.size(); ++two) { if (nums[one] + nums[two] == target) { t.push_back(one); t.push_back(two); return t; } } } return t; } };
時間複雜度: 兩個迴圈都是n個元素遍歷,即O($n^2$).
空間複雜度: O(1).
解法2
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> t; std::unordered_map<int,int> m; for (int one = 0; one < nums.size(); ++one) { int result = target - nums[one]; auto fiter = m.find(result); if (fiter != m.end()) { t.push_back(fiter->second); t.push_back(one); return t; } m[nums[one]] = one; } return t; } };
時間複雜度: 一個迴圈加上一個查詢,由於unordered_map是hash實現,其查詢效率O(1),所以最後的複雜度O(n).
空間複雜度: O(n).