给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
方法一:我使用递归的方法来做的,但是这个方法比较麻烦。
方法二的思路是:遍历数组,用目标数减去数组里面的每一个数,然后判断得到的结果是否也在数组中,如果存在,就返回对应的下标。源代码在网上有,我就不写了
public int[] twoSum(int[] nums, int target) {
int count = 0;
int temp = 0;
int[] array = new int[2];
int[] sums2 = new int[nums.length - 1];
int[] sums3 = new int[nums.length - 1];
for (int i = 1; i < nums.length; i++) {
int sum = nums[temp] + nums[i];
sums2[i - 1] = nums[i];
while (sum == target) {
array[0] = temp;
array[1] = i;
return array;
}
}
count++;
sums3 = twoSum(sums2, target);
for (int j = 0; j < sums3.length; j++) {
sums3[j] = sums3[j] + count;
}
return sums3;
}