/**
* 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值
* 的那 两个 整数,并返回它们的数组下标。
* 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
* 你可以按任意顺序返回答案。
* 输入:nums = [2,7,11,15], target = 9
* 输出:[0,1]
* 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/two-sum
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class Demo1 {
public static void main(String[] args) {
int[] nums = new int[]{3,3};
int[] ints = twoSum(nums, 6);
System.out.println(ints[0]);
System.out.println(ints[1]);
}
/**
* 用这个数以此减去数组每一个数,再去找数组里有没有另一个数
* nums = [2,7,11,15], target = 9 // [3 3] 0 1 =6
*/
public static int[] twoSum(int[] nums, int target) {
//新建一个存储找到索引的数组,第一个元素致为-1 ,以免为0判断失误
int[] arr = new int[2];
arr[0] = -1;
for (int i = 0; i < nums.length; i++) {
//如果能找到数字A,就证明相加等于target
int a = target - nums[i];
//需要查找的数组,不能为数字a ,需要找数字b
for (int j = 0; j < nums.length; j++) {
if (nums[j] == a && j != i) {
//如果找到就放到数组里面
arr[0] = j;
break;
}
}
if (arr[0] != -1) {
arr[1] = i;
break;
}
}
return arr;
}
}