题目:
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
public class Solution {
public static void main(String[] args) {
int[] array = {1,2,3,5,3};
int[] ints = twoSum(array, 9);
if (!ObjectUtils.isEmpty(ints)){
for (int anInt : ints) {
System.out.println(anInt);
}}
System.out.println("输入有误,请重新输入!");
}
public static int[] twoSum(int[] nums, int target) {
int[] results = new int[2];
Integer integerTarget = Integer.valueOf(target);
for (int i = 0; i < nums.length; i++) {
for (int j = nums.length - 1; j > i; j--) {
int sum = nums[i] + nums[j];
if (integerTarget.equals(sum)) {
results[0] = i;
results[1] = j;
return results;
}
}
}
return null;
}
}
法2:
public class Solution2 {
public static void main(String[] args) {
int[] array = {1,2,3,5,9};
int[] ints = twoSum(array, 11);
if (!ObjectUtils.isEmpty(ints)){
for (int anInt : ints) {
System.out.println(anInt);
}
}
}
public static int[] twoSum(int[] nums, int target) {
int[] results = new int[2];
Integer integerTarget = Integer.valueOf(target);
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
//遍历整个数组,将key设为数组的值,value设为数组下标
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])){
results[0] = i;
results[1] = map.get(nums[i]);
return results;
}
//将目标值减去元素的值放进map中
map.put(target-nums[i],i);
}
return results;
}
}