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].
分析
将数组放入HashMap中,然后遍历数组,如果目标值-num等于数组中的另一个值时,并且不是本值,那么这两个值就是我们需要的值。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] answer=new int[2];
HashMap<Integer,Integer> map=new HashMap();
for(int i=0;i<nums.length;i++){
map.put(nums[i],i);
}
for(int j=0;j<nums.length;j++){
int b=target-nums[j];
if(map.containsKey(b)&&j!=map.get(b)){
return new int[]{j,map.get(b)};
}
}
return answer;
}
}
最后
以上就是正直台灯最近收集整理的关于LeetCode第一道题---Two Sum的全部内容,更多相关LeetCode第一道题---Two内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复