题目
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**].
解法
一:暴力搜索
两个for循环即可
二:使用 HashMap
思路
for循环数组,从HashMap中查找结果,找到则返回结果,否则将该位放入HashMap
代码
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap, Integer> map = new HashMap<>();
int[] result = new int[2];
map.put(nums[0], 0);
for (int i = 1; i < nums.length; i++) {
boolean key = map.containsKey(target - nums[i]);
if (key) {
result[0] = map.get(target - nums[i]);
result[1] = i;
break;
}
map.put(nums[i], i);
}
return result;
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于