Leetcode -- 1. two sum
阿新 • • 發佈:2017-10-02
ice sum because integer pub class sta 索引 use
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),空間復雜度O(1)
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res;//sort(nums.begin(), nums.end()); int start = 0, end = 0; for (int i = 0; i < nums.size(); i++){ for (int j = i + 1; j < nums.size(); j++){ if (nums[i] + nums[j] == target){ res.push_back(i); res.push_back(j);return res; } } } } };
2. 利用hashtable,其實是c++中的map(由於c++中不存在hash_table,所以沒有基於hash_table實現 ),時間復雜度可降至O(nlogn), 但是增加了空間復雜度O(n)
註意的一點是,存入map中的Key 是nums中的值,存入的val是nums中對應的索引。
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res; int tmp; map<int, int> hashtable; for (int i = 0; i < nums.size(); i++){ hashtable[nums[i]] = i; // 首先循環遍歷一次將所有的值存入hashtable中 } for (int i = 0; i < nums.size(); i++){ tmp = target - nums[i]; if (hashtable.find(tmp)!= hashtable.end() && hashtable[tmp]!= i){ // 若是能查找到當前值相對於target的補集 res.push_back(i); res.push_back(hashtable[tmp]); return res; } } } };
Leetcode -- 1. two sum