我的解决方法是brute force;
当数组较小时(<1000)建议方法1;
当数组较大时,建议方法3;
https://leetcode.com/problems/two-sum/solution/
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class Test {
public static int[] twoSum1(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
// int temp = target - nums[i];
for (int j = i + 1; j < nums.length; j++) {
if (nums[j]+nums[i]== target) {
return new int[]{i, j};
}
}
}
// throw new IllegalArgumentException("No two sum solution");
return null;
}
public static int[] twoSum2(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
// throw new IllegalArgumentException("No two sum solution");
return null;
}
public static int[] twoSum3(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>(nums.length);
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
// throw new IllegalArgumentException("No two sum solution");
return null;
}
public static void main(String[] args) {
Random random = new Random(System.currentTimeMillis());
int num = 100;
int MAX=1000;
int[] nums = new int[num];
for (int i = 0; i < nums.length; i++) {
nums[i]=random.nextInt(MAX);
}
System.out.println("nums = " + Arrays.toString(nums));
long start,stop;
start = System.nanoTime();
int[] ints = twoSum1(nums, 9);
stop = System.nanoTime();
System.out.println("method 1 cost "+(stop-start)+"ns");
start = System.nanoTime();
int[] ints1 = twoSum2(nums, 9);
stop = System.nanoTime();
System.out.println("method 2 cost "+(stop-start)+"ns");
start = System.nanoTime();
int[] ints2 = twoSum2(nums, 9);
stop = System.nanoTime();
System.out.println("method 3 cost "+(stop-start)+"ns");
System.out.println("ints = " + Arrays.toString(ints));
}
}