package com.darwin.pikachu.example;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.ArrayTable;
import com.google.common.collect.Table;
import java.util.*;
public class Test {
public static void main(String[] args) {
int[] a = new int[]{2,7,11,15};
int[] result = sum(a,9);
int[] ints = sum2(a, 9);
System.out.println(JSON.toJSON(result));
System.out.println(JSON.toJSON(ints));
}
/**
* 数组中查找和为num的两个
* @param a
* @param num
* @return
*/
public static int[] sum(int[] a, int num) {
for (int i = 0; i < a.length; i++) {
int t = num - a[i];
for (int j = i + 1; j < a.length; j ++) {
if (t == a[j]) {
int[] result = new int[]{i, j};
return result;
}
}
}
return null;
}
/**
* 数组中查找和为num的两个
* @param a
* @param num
* @return
*/
public static int[] sum2(int[] a, int num) {
Map<Integer, Integer> indexMap = new HashMap<>();
for (int i = 0; i < a.length; i++) {
int t = num - a[i];
if (indexMap.containsKey(t)) {
return new int[]{i, indexMap.get(t)};
}
indexMap.put(a[i], i);
}
return null;
}
}