点击查看答案
- 方案1:在排序时带上索引下标,即排序的对象是元组`(num, index)`的数组。这个技术**一定要掌握**,许多题目都会用到。
- 方案2:使用index() 查找,已经放到另外一个题解中讲解。
## 复杂度
- 时间复杂度: `O(N * log N)`.
- 空间复杂度: `O(N)`.
## Python
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
num_index_list = [(num, i) for i, num in enumerate(nums)]
num_index_list.sort()
left = 0
right = len(nums) - 1
while left < right:
sum_ = num_index_list[left][0] + num_index_list[right][0]
if sum_ == target:
return [num_index_list[left][1], num_index_list[right][1]]
if sum_ < target:
left += 1
continue
right -= 1
```
## Other languages
```java
// Welcome to create a PR to complete the code of this language, thanks!
```
## 思路 2
1. `Map`中,`key`是`num`,`value`是数组`index`。
2. 遍历数组,如果`target - num`在`Map`中,返回。反之,将`num`加入`Map`中。
## 步骤
1. `Map`中,`key`是`num`,`value`是数组`index`。
```javascript
let numToIndex = new Map()
for (let i = 0; i < nums.length; i++) {
numToIndex.set(nums[i], i)
}
```
2. 遍历数组,如果`target - num`在`Map`中,返回。反之,将`num`加入`Map`中。
```javascript
let numToIndex = new Map()
for (let i = 0; i < nums.length; i++) {
if (numToIndex.has(target - nums[i])) { // 1
return [numToIndex.get(target - nums[i]), i] // 2
}
numToIndex.set(nums[i], i)
}
```
## 复杂度
- 时间复杂度: `O(N)`.
- 空间复杂度: `O(N)`.
## Java
```java
class Solution {
public int[] twoSum(int[] nums, int target) {
var numToIndex = new HashMap