一、给定一个数组,找出数组中的两个数字相加之后等于目标值的俩数字下标
示例: 数组[1, 5, 2, 7, 9, 8],目标值:15,
输出下标: 3,5
package com.example.dzx.datastrctet;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author 500007
* @ClassName:
* @Description: 给定一个数组,找出数组中的两个数字相加之后等于目标值的俩数字下标
* 示例: 数组[1, 5, 2, 7, 9, 8],目标值:15,输出下标,3,5
* @date 2022年04月22日 15:07:05
*/
public class TwoSum {
/**
* 双层for循环:暴力穷举法
*
* @param xx
* @param target
* @return
*/
public int[] twoSum1(int[] xx, int target) {
int[] indexs = new int[2];
for (int i = 0; i < xx.length; i++) {
for (int j = i + 1; j < xx.length; j++) {
if (xx[i] + xx[j] == target) {
indexs[0] = i;
indexs[1] = j;
}
}
}
return indexs;
}
/**
* 利用map缓存倒推计算法
*
* @param xx
* @param target
* @return
*/
public int[] twoSum2(int[] xx, int target) {
//key为元素值,value为元素下标
int[] indexs = new int[2];
Map<Integer, Integer> map = new HashMap<>(xx.length);
for (int i = 0; i < xx.length; i++) {
int anotherValue = target - xx[i];
Integer anotherIndex = map.get(anotherValue);
if (anotherIndex == null) {
map.put(xx[i], i);
} else {
indexs[0] = anotherIndex;
indexs[1] = i;
break;
}
}
return indexs;
}
public static void main(String[] args) {
//给定一个数组,找出数组中的两个数字相加之后等于目标值的俩数字下标
int[] xx = new int[]{1, 5, 2, 7, 9, 8};
int target = 15;
System.out.println(Arrays.toString(new TwoSum().twoSum1(xx, target)));
System.out.println(Arrays.toString(new TwoSum().twoSum2(xx, target)));
}
}
运行代码,输出如下: