Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
- Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than
O(n2)
time complexity?
給定一個整數陣列 nums
和一個整數 target
,返回兩個數字的索引,使它們的和等於 target
。
您可以假設每個輸入都只有一個解,並且您不可以重複使用相同的元素。
您可以以任何順序返回答案。
範例 1:
輸入: nums = [2,7,11,15], target = 9
輸出: [0,1]
解釋: 因為 nums[0] + nums[1] == 9,所以我們返回 [0, 1]。
範例 2:
輸入: nums = [3,2,4], target = 6
輸出: [1,2]
範例 3:
輸入: nums = [3,3], target = 6
輸出: [0,1]
限制:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
- 只有一個有效答案存在。
進階問題: 您能否提供一個時間複雜度小於
O(n2)
的算法?
[leetcode] 1. Two Sum
Given an array of integers
nums
and an integertarget
, return indices of the two numbers such that they add up totarget
.You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Example 2:
Example 3:
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
O(n2)
time complexity?給定一個整數陣列
nums
和一個整數target
,返回兩個數字的索引,使它們的和等於target
。您可以假設每個輸入都只有一個解,並且您不可以重複使用相同的元素。
您可以以任何順序返回答案。
範例 1:
範例 2:
範例 3:
限制:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
O(n2)
的算法?解題技巧待更新