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].
idea
本題和lintcode 題目有點(diǎn)區(qū)別,本題允許兩個(gè)重復(fù)數(shù)出現(xiàn),比如數(shù)組 [3, 3] target = 6,如果按照 lintcode 代碼會(huì)出現(xiàn),results = [1, 1] 而實(shí)際上我們要的是 [0, 1],所以需要用
if (hash.containsKey(complement) && hash.get(complement) != i)做一個(gè)特判,保證在給 results[0] 和 results[1] 賦值時(shí)不出現(xiàn)重復(fù),但還有一點(diǎn)需要強(qiáng)調(diào)的是之前在賦值時(shí)寫的代碼是results[1] = hash.get(nums[i]),這么寫在出現(xiàn)上述 [3, 3] 這種帶有元素的重復(fù)數(shù)組會(huì)有問題,盡管 if 條件句做了特判,但賦值時(shí)可能hash.get(complement)和hash.get(nums[i])得到的是同一個(gè)值,所以要直接寫results[1] = i
Code
- 遍歷兩次 hashTable
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] results = new int[2];
if (nums == null || nums.length == 0) {
return results;
}
Map<Integer, Integer> hash = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
hash.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (hash.containsKey(complement) && hash.get(complement) != i) {
results[0] = hash.get(complement);
results[1] = i;
}
}
return results;
}
}
- 遍歷一次 hashTable
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] results = new int[2];
if (nums == null || nums.length == 0) {
return results;
}
Map<Integer, Integer> hash = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (hash.containsKey(complement) && hash.get(complement) != i) {
results[0] = hash.get(complement);
results[1] = i;
}
hash.put(nums[i], i);
}
return results;
}
}