leetcode-1.两数之和 | LIXI.FUN
0%

leetcode-1.两数之和

题目链接

1. 两数之和

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int[] twoSum(int[] nums, int target) {

// 没有重复元素,可以构建 value 对应 index 的哈希表
Map<Integer, Integer> valueToIndex = new HashMap<>();

for (int i = 0; i < nums.length; i++) {
int preNum = target - nums[i];
if (valueToIndex.containsKey(preNum)) {
return new int[] {valueToIndex.get(preNum), i};
}
valueToIndex.put(nums[i], i);
}

throw new RuntimeException();
}
}

复杂度分析

  • 时间复杂度: O(N)
  • 空间复杂度: O(N)

其中 N 是数组中元素数量

相似题目

觉得有收获就鼓励下作者吧