0
点赞
收藏
分享

微信扫一扫

LeetCode Top-100 T1-两数之和


题目描述:

给定一个整数数组 ​​nums​​​ 和一个目标值 ​​target​​,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解题思路:

题目使用最暴力的遍历,直接相加对比得出结果


Java代码版本1如下:

class Solution {
public int[] twoSum(int[] nums, int target) {

for (int i = 0; i < nums.length-1; i++) {
for (int j = i+1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
int[] arr2 = {i,j};
return arr2;
}
}
}

throw new IllegalArgumentException("No two sum solution");
}
}

Java代码版本2如下:

注:版本2代码比版本1慢了10ms左右

class Solution {
public int[] twoSum(int[] nums, int target) {
int[] arr = new int[2];

for (int i = 0; i < nums.length-1; i++) {
for (int j = i+1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
arr[0] = i;
arr[1] = j;
}
}
}
return arr;
}
}



举报

相关推荐

0 条评论