给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
这题相对来说思路简单很多,我用的方法也是暴力,就是遍历;
但一开始我的思路还是出了点差错,我首先是遍历nums这个数组,当nums数组中的元素小于给定的target,我才会去把数组中剩下的元素拿去和target-nums[i]的值作比较;
但是bug就来了,就是因为两数之和,所以我一直觉得target的值只能是从nums数组里两个小于它的数相加得到,但是我忘记负数了,所以就。。。。。 改了一下,然后把能跑的代码给写了出来,如下
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] arr = new int[2];
for(int i = 0; i < nums.length; i++){
int temp = target - nums[i];
for(int j = i+1; j < nums.length; j++){
if(temp == nums[j]){
arr[0] = i;
arr[1] = j;
}
}
}
return arr;
}
}
写得没有特别简介噢,我特意看了下别人写的,是这样的:
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException(“No two sum solution”);
}
}
主要的区别在于那个数组的创建我觉得,
最后的时候直接new int[] {i,j};
作者:LeetCode
链接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-2/