[LeetCode] 1 Two Sum
阿新 • • 發佈:2017-09-10
.cn des www. 時間復雜度 pre ret tco ++ rip
原題地址:
https://leetcode.com/problems/two-sum/description/
題目:
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].
解法:
這是很簡單的一道題目,也是LeetCode的第一道題,首先想到的肯定是最基本的暴力方法,用兩層循環就解決了。
//解法一
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> temp; int size = nums.size(); for (int i = 0; i < size - 1; i++) { for (int j = i + 1; j < size; j++) { if (nums[i] + nums[j] == target) { temp.push_back(i); temp.push_back(j); break; } } } return temp; } };
這個算法的時間復雜度為O(n^2),假如不break的話,是會TLE的。
實際上有很多時間復雜度為O(n)的解法,我自己的另一種方法就是:新開一個數組a,把nums裏面的值作為新數組a的下標,nums各元素的位置作為新數組a中的值。循環一遍,當a[target - num[i]]不為0時,就說明i和當前的a[target - num[i]]就是所要的結果。有點類似於桶排序的想法;但值得註意的是由於nums裏面元素的值有可能為負數,不能作為下標,因此要作一些變化:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> temp; int size = nums.size(); int * a = new int[1000000]; for (int i = 0; i < 1000000; i++) { a[i] = 0; } for (int i = 0; i < size; i++) { a[nums[i] + 500000] = i; } for (int i = 0; i < size; i++) { if (a[target - nums[i] + 500000]) { temp.push_back(i); temp.push_back(a[target - nums[i] + 500000]); break; } } delete [] a; return temp; } };
寫起來有點復雜,但是具體的思想就在裏面。其實也可以用C++裏面的容器來做,更簡單(下面的代碼來自於:http://www.cnblogs.com/grandyang/p/4130379.html)
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> m; vector<int> res; for (int i = 0; i < nums.size(); ++i) { m[nums[i]] = i; } for (int i = 0; i < nums.size(); ++i) { int t = target - nums[i]; if (m.count(t) && m[t] != i) { res.push_back(i); res.push_back(m[t]); break; } } return res; } };
[LeetCode] 1 Two Sum