LeetCode Two Sum時間複雑度O(n)解法試行バージョン1
2040 ワード
テーマは以下の通りです
Gven an array of integers、return indices of the two numbers such that they add up to a specific taget.
You may asume that each input would have exactly one solution,and you may not use the さとめ element twice.
Example:
notepad++で書いたものは、デバッグしていません..)変更します.全体の考え方はまだ変化していません.この方法はvectorの中の数が全部正しいだけで、しかもあまり大きい場合はいけません.そうでないと、オフラインまたはメモリ申請が失敗します.
Gven an array of integers、return indices of the two numbers such that they add up to a specific taget.
You may asume that each input would have exactly one solution,and you may not use the さとめ element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
第一版解法試み// nums 0 ,
// nums 0 ,
// target target
class Solution {
public:
vector twoSum(vector& nums, int target) {
vector HashTable(target + 1); //+1 target , nums target 0
vector ret;
for (unsigned int i = 0; i < nums.size(); i++) //" ",vector
{
if (nums[i] <= target) // , target target
HashTable[nums[i]] = i; // nums[i]
}
// HashTable nums target nums , HashTable[i] HashTable[target - i] ,
for (unsigned int i = 0; i <= target; i++)
{
// , nums[i] i nums[i] target-i , ,nums[0] 0 nums[target] target nums[target] 0 nums[0] targe
if (i == HashTable[i] && HashTable[target - i] == (target - i) || i == HashTable[target - i] && HashTable[i] == (target - i))
{
ret.push_back(HashTable[i]);
ret.push_back(target - HashTable[i]);
break;
}
if (HashTable[i] > 0 && HashTable[target - i] > 0) //
{
ret.push_back(HashTable[i]);
ret.push_back(HashTable[target - i]);
break;
}
}
return ret;
}
};
18/1/7の更新で、偶然に戻ってきたのは下付きではないことが分かりました.そして、retはデフォルトの2つの空き値があります.notepad++で書いたものは、デバッグしていません..)変更します.全体の考え方はまだ変化していません.この方法はvectorの中の数が全部正しいだけで、しかもあまり大きい場合はいけません.そうでないと、オフラインまたはメモリ申請が失敗します.