[LeetCode] TwoSum兩數之和

[LeetCode] ?TwoSum兩數之和

Given an array of integers, returnindicesof the two numbers such that they add up to a specific target.

You may assume that each input would haveexactlyone solution, and you may not use thesameelement twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0,1].

用暴力搜索,算法的時間復雜度是O(n^2)

/**?

* Time Limit Exceeded?

*/

class Solution ?{

public:? ??

vector<int>twoSum(vector<int>&numbers, int target)

{? ? ? ? vector<int> res;

? ? ? ? ?for (int i = 0; i < numbers.size(); ++i) {

? ? ? ? ? ? ? for (int j = i + 1; j < numbers.size(); ++j) {

? ? ? ? ? ? ? ? ? ? if (numbers[j] + numbers[i] == target) {

? ? ? ? ? ? ? ? ? ? ? ? ? ? res.push_back(i + 1);

? ? ? ? ? ? ? ? ? ? ? ? ? ? res.push_back(j + 1);

? ? ? ? ? ? ? ? ? ?}

? ? ? ? ? ? ?}

}

? ? ? ? ? ?return res;

}

};

那么只能想個O(n)的算法來實現,整個實現步驟為:先遍歷一遍數組,建立map數據,然后再遍歷一遍,開始查找,找到則記錄index。代碼如下:

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;

}

};

更簡單的寫法

class Solution {

public:? ? vector<int> ?twoSum(vector<int> & nums, int target) {? ? ??

? ? ? ? ? ?unordered_map<int,int> m;

? ? ? ? ? for (int i = 0; i < nums.size(); ++i) {

? ? ? ? ? ? ? ? if (m.count(target - nums[i])) {

? ? ? ? ? ? ? ? ? ? ? return {i, m[target - nums[i]]};

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ?m[nums[i]] = i;

}

return {};

}

};

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容