给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解题思路:
输入:1.整数数组;2.目标值
输出:数组中和为目标值的两个数的数组角标
循环数组,用目标值减去当前值,用差值去数组中遍历。
遍历成功:返回差值角标,结束所有循环,方法返回差值与当前值角标组成的数组;
遍历失败:返回-1,继续循环数组
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] returnValue = new int[2];
int aLength = nums.length;
int target2 = 0;
int targetTemp = 0;
for(int i = 0; i < aLength; i++){
targetTemp = target - nums[i];
target2 = toSumTemp(nums, aLength, target, (i+1), targetTemp);
if(target2 != -1){
returnValue[0] = i;
returnValue[1] = target2;
return returnValue;
}
}
return returnValue;
}
public int toSumTemp(int[] nums, int aLength, int target, int target1, int targetTemp){
for(int j = target1; j < aLength; j++){
if(targetTemp == nums[j]){
return j;
}
}
return -1;
}
}
