题目链接:https://leetcode.com/problems/two-sum/
题目:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
解题思路:
这道题特别纪念一下,第一次面试被问到的题,可惜当时还没在 leetcode 上做过这题。。。
- 遍历数组,将所有元素及其下标放到 HashMap 中。
- 再次遍历数组,用 target 数减去当前元素,获得要找的另一个元素的值 another。
- 在 HashMap 中查找 another 这个元素是否存在。
- 若存在,检查该元素下标是否等于当前元素的下标(即,找到的元素与当前遍历到的元素不能是同一个,下标不能相同)
- 若不存在,继续遍历数组中下一个元素
注意:
要找的另一个元素的值有可能等于当前遍历到的元素的值。例如
[3, 2, 4] 6
输出下标时,只能输出 [2,3],而不是 [1,1]。
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
if(nums == null || nums.length == 0)
return indices;
HashMap<Integer, Integer> map = new HashMap();
int len = nums.length;
for(int i = 0; i < len; i ++)
map.put(nums[i], i + 1);
for(int i = 0; i < len; i ++) {
int another = target - nums[i];
if(map.containsKey(another) && map.get(another) != i + 1) {
indices[0] = i + 1;
indices[1] = map.get(another);
break;
}
}
return indices;
}
}
16 / 16 test cases passed.
Status: Accepted
Runtime: 328 ms