title: Two Sum
tags:
- two-sum
- simple
- hash
- No.1
- integer
Problem
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].
Solution
Brute-Force
Brute-Force runs in O(n^2):
class Solution {
public int[] twoSum(int[] nums, int target) {
// O(n^2)
for (int i=0; i<nums.length-1; i++) {
for (int j=i+1; j<nums.length; j++) {
if (nums[i] + nums[j] == target)
return new int[] {i, j};
}
}
throw new IllegalArgumentException("No solution");
}
}
Twice Hash
Hash twice: First takes O(n) to build HashMap. Second to search the complement O(n) times in O(1):
import java.util.*;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> val_loc = new HashMap<Integer, Integer>();
// O(n)
for (int i=0; i<nums.length; i++) {
val_loc.put(nums[i], i);
}
// O(n)
for (int i=0; i<nums.length; i++) {
// O(1)
Integer j = val_loc.get(target - nums[i]);
if (j != null) {
if (j != i) {
return (i < j) ? (new int[] {i, j}) : (new int[] {j, i});
}
}
}
throw new IllegalArgumentException("No solution");
}
}
Once Hash
Search the existed elements in table while insert new pairs to it. Thus loop one time in O(n):
import java.util.*;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> val_loc = new HashMap<Integer, Integer>();
// O(n)
for (int i=0; i<nums.length; i++) {
// O(1)
Integer j = val_loc.get(target - nums[i]);
if (j != null) {
if (j != i) {
return (i < j) ? (new int[] {i, j}) : (new int[] {j, i});
}
}
val_loc.put(nums[i], i);
}
throw new IllegalArgumentException("No solution");
}
}
网友评论