数组元素内两元素相加等于目标值,返回数组下标

来自 作者reed分享
import java.util.Arrays;
import java.util.HashMap;

/**
* @auto dh
* @create 2020-03-29-12:40
*/
public class Test019 {
public static int[] testArith() {
int[] arr = {12, 14, 18, 20};
HashMap<Integer, Integer> hashMap = new HashMap<>();
int target = 32;

for (int i = 0; i < arr.length; i++) {
int value = target - arr[i];
if (hashMap.containsKey(value)) {
return new int[]{hashMap.get(value), i};
}
hashMap.put(arr[i], i);
}

return null;

}

public static void main(String[] args) {
System.out.println(Arrays.toString(testArith()));
}
}

猜你喜欢

转载自www.cnblogs.com/kukai/p/12592778.html