1. 题目
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].
2. 关键算法
哈希表的使用。
3. 代码实现
import java.util.Arrays;
import java.util.HashMap;
/**
* @author: UniqueZ_
* @file: the first question of leetcode - two sum
* @date: 2017-06-22
*/
public class TwoSum {
private int[] arr;
private int target;
public TwoSum(int[] arr, int target) {
this.arr = arr;
this.target = target;
}
// force method - O(n^2)
public int[] twoSum_force() {
int arrLength = arr.length;
for (int i = 0; i < arrLength; i++) {
for (int j = i; j < arrLength; j++) {
if (arr[i] + arr[j] == target) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No solution founded.");
}
// hash method - O(n)
public int[] twoSum_hash() {
HashMap<Integer, Integer> hMap = new HashMap<>();
int arrLength = arr.length;
for (int i = 0; i < arrLength; i++) {
if (hMap.containsKey(target - arr[i])) {
return new int[] { hMap.get(target - arr[i]), i };
}
hMap.put(arr[i], i);
}
throw new IllegalArgumentException("No solution founded.");
}
// main - test the two methods
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 3, 4 };
int target = 4;
int[] result = new int[2];
TwoSum object = new TwoSum(arr, target);
result = object.twoSum_hash();
System.out.println(Arrays.toString(result));
}
}