给定一个整数数组 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:当时看题的第一想法就是用暴力法,用两层for循环遍历数组,直至找到两个相加等于target值的元素。将元素存放在数组中,然后返回数组。很想换种方法,但自己能力不足,看到题解有一种哈希表的解决方法。等到学完哈希表,再回来解一遍。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] arr = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (target == nums[i] + nums[j]) {
arr[0] = i;
arr[1] = j;
return arr;
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
第一次没有抛异常时,给出错误:missing return statement。
是因为return 语句在if判断中,可能会没有返回值才引发的错误。第一次没有注意,做个笔记。