LeetCode #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].
翻譯
給定一個陣列,返回兩個數字的下標索引,使它們相加到特定值。
你可以認為輸入的每個測試用例只有一個特定解且陣列中沒有值相同的元素。
示例:
陣列 nums=[2, 7, 11, 15],目標target=9,
因為nums[0] + nums[1] = 2 + 7 = 9,
返回[0,1].
分析
直接用BF(Brute Force)暴力求解就是通過兩層迴圈巢狀完成,時間複雜度O(n2),會超時,不是一個很好的方法,此處不再贅述。
第二種方法就是以時間換空間,把陣列存到一個map裡面,map的key為陣列的值,map的value為陣列的下標。這樣只需要遍歷原陣列,檢視a=target-nums[i]的值在不在map的下標中,如果存在且map[a]與i不相等,則這兩個值就是需要返回的下標。
時間複雜度O(n),空間複雜度O(n)。
程式碼如下:
程式碼(C++)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> Myset;
vector<int> results;
for (auto tmp = nums.begin(); tmp<nums.end(); tmp++) Myset[*tmp] = tmp - nums.begin();
for (auto tmp = Myset.begin(); tmp != Myset.end(); tmp++) cout << (*tmp).first << " "<< (*tmp).second<<endl;
for (auto tmp = nums.begin(); tmp < nums.end(); tmp++)
{
if (Myset.find(target - *tmp) != Myset.end()&& (*Myset.find(target - *tmp)).second!=(tmp - nums.begin()))
{
results.push_back(tmp - nums.begin());
results.push_back(Myset[target - *tmp]);
break;
}
}
return results;
}
};
相關文章
- Leetcode 1 two sumLeetCode
- LeetCode | 1 Two SumLeetCode
- [LeetCode]1.Two SumLeetCode
- LeetCode----1. Two SumLeetCode
- LeetCode1:Two SumLeetCode
- [LeetCode]1. Two SumLeetCode
- LeetCode OJ : 1 Two SumLeetCode
- LeetCode-1 Two SumLeetCode
- python: leetcode - 1 Two SumPythonLeetCode
- [leetCode][012] Two Sum (1)LeetCode
- Leetcode-1 Two Sum(Java) -by zzyLeetCodeJava
- Leetcode Two SumLeetCode
- Leetcode-Two SumLeetCode
- Two Sum leetcode javaLeetCodeJava
- 【LeetCode 1_陣列_雜湊表】Two SumLeetCode陣列
- LeetCode: Two sum(兩數之和)LeetCode
- LeetCode Problem-Sum of Two IntegersLeetCode
- [leetCode][013] Two Sum 2LeetCode
- [LeetCode] Two Sum 兩數之和LeetCode
- LeetCode-two sum:python解答陣列問題LeetCodePython陣列
- leetcode 371. Sum of Two IntegersLeetCode
- LeetCode 之 JavaScript 解答第一題 —— 兩數之和(Two Sum)LeetCodeJavaScript
- LeetCode Two Sum(001)解法總結LeetCode
- python leetcode 之兩數之和(two sum)PythonLeetCode
- LeetCode-Two Sum III - Data structure designLeetCodeStruct
- 371. Sum of Two Integers--LeetCode RecordLeetCode
- JavaScript的two-sum問題解法JavaScript
- 【Leetcode】167. Two Sum II - Input array is sortedLeetCode
- LeetCode 1.Two NumsLeetCode
- 力扣.1 兩數之和 N 種解法 two-sum力扣
- 653-Two Sum IV - Input is a BST
- 簡單演算法題:leetcode-1 兩數之和演算法LeetCode
- 用python手刃Leetcode(1):兩數之和【簡單題】PythonLeetCode
- 簡單探討sum()函式返回null的問題函式Null
- 【LeetCode】簡單題目集LeetCode
- LeetCode 1 兩數之和(簡單)LeetCode
- LeetCode C++ 1464. Maximum Product of Two Elements in an Array【Array/Sort】簡單LeetCodeC++
- LeetCode 第 231 題 (Power of Two)LeetCode