文章目录
- 1. 两数之和-力扣 1 题
1. 两数之和-力扣 1 题
思路:
- 循环遍历数组,拿到每个数字x
- 以target-x作为key到map中查找
-
- 若没找到,将x 作为key,它的索引作为value 存入map
-
- 若找到了,返回 x 和它配对数的索引即可
-
class Solution {public int[] twoSum(int[] nums, int target) {HashMap<Integer, Integer> map = new HashMap<>();for (int i = 0; i < nums.length; i++) {int x = nums[i];int y = target-x;if (map.containsKey(y)) {return new int[]{i, map.get(y)};} else {map.put(x, i);}}return null;}
}