题目
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].
解法思路(一)
- 游标
i
在[0, nums.length)
间遍历,每遍历到一个数,就在其前遍历过的数中找target - nums[i]
,这个找的动作是依赖于哈希表完成的(HashMap),如果找到了,就得到解了,如果没找到,就把当前数放入哈希表,键为nums[i]
,值为i
;
解法实现(一)
时间复杂度
- O(N);
空间复杂度
- O(N);
关键词
哈希表
HashMap
package leetcode._1;
import java.util.HashMap;
public class Solution1_1 {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> toFindComplement = new HashMap<>(nums.length);
for(int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
Integer indices = toFindComplement.get(complement);
if (indices != null) {
return new int[]{indices.intValue(), i};
}
toFindComplement.put(nums[i], i);
}
throw new RuntimeException("No result!");
}
public static void main(String[] args) {
int[] arr = {2, 7, 11, 15};
int[] result = (new Solution1_1()).twoSum(arr, 9);
for (int i = 0; i < result.length; i++) {
if (i == result.length - 1) {
System.out.println(result[i]);
} else {
System.out.print(result[i] + " ");
}
}
System.out.println(result.length);
}
}