霍金昨天回到了属于他的宇宙星空,他本不属于这里,他属于宇宙
前言,准备开始看LeetCode,不知道什么时候能看完,但是有什么关系呢?有时候做一些事,只是为了兴趣而已,何必要把自己搞的那么辛苦,那么信誓旦旦。
LeetCode官网:https://leetcode.com/
我是直接用GitHub授权登录的。
问题
给定一个整数数组,返回这两个数字的索引,使它们合计成一个特定的目标。
举例
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解法一(不经思考,暴力解决)
public 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[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
时间复杂度:O(n^2)
空间复杂度:O(1)
解法二(双向哈希表)
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
时间复杂度:O(n)
空间复杂度:O(n)
解法三(一次散列表)
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
时间复杂度:O(n)
空间复杂度:O(n)
测试用例
具体解法代码,建议不借助IDE手写
public class TwoSum {
public static void main(String[] args) {
//学习两种声明数组的方式
int[] nums = new int[]{2, 7, 11, 15};
int[] num = {2, 71, 11, 15, 7};
int target = 9;
int[] arr = twoSum(num, target);
System.out.println(Arrays.toString(arr));
}
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
借用知乎的一首打油诗
明有科举八股,
今有leetcode。
leetcode定题目且重答案背诵。
美其名曰:“practice makes perfect.”
为何今不如古?
非也非也,
科举为国取士,
leetcode为Google筛码工,
各取所需也。