长期更新,对使用 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;
}
}
本文作者 Auther:Soptq
本文链接 Link: https://soptq.me/2018/09/20/leetCode1/
版权声明 Copyright: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处。 Content on this site is licensed under the CC BY-NC-SA 4.0 license agreement unless otherwise noted. Attribution required.
发现存在错别字或者事实错误?请麻烦您点击 这里 汇报。谢谢您!