给定一个数组或输入一个数组,在数组里取三个数使这三个数等于一个特定的值target,并返回这三个数的下标,要求不能有重复的组合。
java
package 例题;
import java.util.HashMap;
//三数之和
public class Test1 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 5, 7, 9, 11, 13, 16, 14, 15,18, 94, 42, 35};
int target = 40;//三数之和
HashMap<Integer, Integer> map = new HashMap<>();
HashMap<Integer, Integer> map2 = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
map.put(arr[i], i);
}
for (int i = 0; i < arr.length; i++) {
int w =target-arr[i];
int[] xx = get(arr,w);
if(xx[0]!=-1){
if(i!=xx[0]&&i!=xx[1]){
if(map2.get(i)==null||map2.get(xx[0])==null){
map2.put(i,i);
map2.put(xx[0],xx[0]);
map2.put(xx[1],xx[1]);
System.out.println("位置:"+i+","+xx[0]+","+xx[1]);
}
}
}
}
}
public static int[] get(int[] arr,int target){
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
map.put(arr[i], i);
}
for (int i = 0; i < arr.length; i++) {
int w = target - arr[i];
Integer index = map.get(w);
if (index != null) {
return new int[]{i, index};
}
}
return new int[]{-1,-1};
}
}