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
- python: leetcode - 1 Two SumPythonLeetCode
- LeetCode: Two sum(兩數之和)LeetCode
- leetcode 371. Sum of Two IntegersLeetCode
- LeetCode Two Sum(001)解法總結LeetCode
- LeetCode 之 JavaScript 解答第一題 —— 兩數之和(Two Sum)LeetCodeJavaScript
- python leetcode 之兩數之和(two sum)PythonLeetCode
- 【Leetcode】167. Two Sum II - Input array is sortedLeetCode
- 1.兩數之和 Two Sum
- 用python手刃Leetcode(1):兩數之和【簡單題】PythonLeetCode
- 【LeetCode】簡單題目集LeetCode
- 簡單演算法題:leetcode-1 兩數之和演算法LeetCode
- LeetCode C++ 1464. Maximum Product of Two Elements in an Array【Array/Sort】簡單LeetCodeC++
- 力扣.1 兩數之和 N 種解法 two-sum力扣
- LeetCode 1 兩數之和(簡單)LeetCode
- 653-Two Sum IV - Input is a BST
- 簡單探討sum()函式返回null的問題函式Null
- leetcode Sum系列LeetCode
- Leetcode Path SumLeetCode
- 001-ksum 求符合條件的 k 個數 1. Two Sum/15. 3Sum/18. 4Sum/
- 001,Two Sum(求兩數的和)
- Leetcode 231 Power of TwoLeetCode
- Leetcode 39 Combination SumLeetCode
- abc098D Xor Sum 2(two point)
- 18. 4Sum(Leetcode每日一題-2020.10.05)LeetCode每日一題
- Leetcode 29 Divide Two IntegersLeetCodeIDE
- LeetCode 2 Add Two NumbersLeetCode
- LeetCode | 349 Intersection Of Two ArraysLeetCode
- Leetcode 231. Power of TwoLeetCode
- 【leetcode 簡單】 第一百零六題 壓縮字串LeetCode字串
- LeetCode簡單演算法題目-JS解法LeetCode演算法JS
- LeetCode:每日一題:27. 移除元素 ——————簡單LeetCode每日一題
- leetcode-39-Combination SumLeetCode
- Leetcode 40 Combination Sum IILeetCode
- Leetcode 15 3SumLeetCode