问题描述:
- 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target的那两个整数,并返回它们的数组下标。
- 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
- 你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
这个问题很简单,核心重点就是在于两数之和要等于target,那我们很容易想到用两个for循环不断去尝试就行了,最终返回两个元素的下标
核心代码:
public static int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) { // j直接从i后面开始遍历
if (nums[i] + nums[j] == target) { // 当满足条件时,直接返回一个下标数组
return new int[]{i, j};
}
}
}
return null;
}
代码解释:
注意到问题描述里强调了“数组中同一个元素在答案里不能重复出现”
举个例子:nums = [1, 2, 3], target = 4
那我们返回的下标应该是[0, 2],而不能是[1,1]
i是从第一个元素开始遍历,j每次只要从i后一位开始就行,减少遍历次数
比如说i=3时,j只要从4开始就行,前面的0,1,2不用去遍历匹配(注意:此时 j=3 是非法的)
同样用nums = [1, 2, 3],target = 4举例:
(i = 0,j = 2) 与 (i = 2, j = 0) 二者的结果是一样的,最终获取的元素都是1和3。
故 j = i + 1既能避免出现非法问题(i = j),又减少了遍历次数
运行效果
完整源代码
package com.practice;
public class two_sum {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
for (int val : twoSum(nums, target)) {
System.out.print(val + " ");
}
}
public static 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[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return null;
}
}