长期更新,对使用 Java 刷 LeetCode 过程中一些有趣的题的感想和启发。 解题源代码仓库

题目

题目链接

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

我的思路

这道题相当的简单,双重循环就可以解决了。

我的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//解决方法
class Solution {
	public int[] twoSum(int[] nums, int target){
		int length = nums.length;
		for (int i = 0;i < (length - 1);i++) {
			for (int j = i + 1;j < length;j++) {
				if (nums[i] + nums[j] == target) {
					return new int[]{i,j};
				}
			}
		}
		return null;
	}
}


发现存在错别字或者事实错误?请麻烦您点击 这里 汇报。谢谢您!