二 、 数组
2.1 两数之和 (暴力算法 — 哈希表算法)
package com.algorithm.arrays;
import java.util.HashMap;
import java.util.Map;
public class TowSum {
public static void main(String[] args) {
int[] input1 = {2, 7, 11, 15};
int target1 = 9;
int[] input2 = {3, 2, 4};
int target2 = 6;
int[] input3 = {3, 3};
int target3 = 6;
int[] input = new int[100000];
for (int i = 0; i < input.length; i++) {
input[i] = input.length - i;
}
int target = 47344;
long start = System.currentTimeMillis();
TowSum towSum = new TowSum();
int[] ints = towSum.twoSumHash1(input, target);
for (int anInt : ints) {
System.out.print(anInt + "\t");
System.out.println(input[anInt]);
}
long end = System.currentTimeMillis();
System.out.println("运行时长 :" + (end - start) + " ms");
}
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
throw new IllegalArgumentException("无解。。。。");
}
public int[] twoSumHash(int[] nums, int target) {
int n = nums.length;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < n; i++) {
int thatNum = target - nums[i];
if (map.containsKey(thatNum) && map.get(thatNum) != i) {
return new int[]{i, map.get(thatNum)};
}
}
throw new IllegalArgumentException("无解。。。。");
}
public int[] twoSumHash1(int[] nums, int target) {
int n = nums.length;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
int thatNum = target - nums[i];
if (map.containsKey(thatNum) && map.get(thatNum) != i) {
return new int[]{map.get(thatNum), i};
} else {
map.put(nums[i], i);
}
}
throw new IllegalArgumentException("无解。。。。");
}
}