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].
給一個整數(shù)數(shù)組驳庭,找到兩個數(shù)使得他們的和等于一個給定的數(shù) target恋腕。
你需要實(shí)現(xiàn)的函數(shù)twoSum需要返回這兩個數(shù)的下標(biāo), 并且第一個下標(biāo)小于第二個下標(biāo)诀豁。注意這里下標(biāo)的范圍是 1 到 n,不是以 0 開頭弛车。
分析
利用hashmap存儲每個元素的值和所在的下標(biāo)赌朋,遍歷一遍斋泄,如果target-nums[i]在map里直接取出index值返回就可以了。leetcode 的第一道題扭吁。
代碼
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++) {
if(map.containsKey(target-nums[i])) {
return new int[] {i, map.get(target-nums[i])};
}
else {
map.put(nums[i], i);
}
}
return new int[]{};
}
}