1. Two Sum
来源:互联网 发布:变女声软件 编辑:程序博客网 时间:2024/05/15 11:38
第一道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].
第一直觉二重循环,我的代码如下:
public int[] twoSum(int[] nums, int target) { int[] indices = new int[] { -1, -1 }; for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { indices[0] = i; indices[1] = j; } } } return indices; }
时间复杂度:
空间复杂度:
这个应该是最轻易能想到的解法
参看答案后发现另两种解法:利用Hash Table,将搜寻第二个匹配解的时间复杂度从
解法一:
A simple implementation uses two iterations. In the first iteration, we add each element’s value and its index to the table. Then, in the second iteration we check if each element’s complement (target - nums[i]target−nums[i]) exists in the table. Beware that the complement must not be nums[i]nums[i] itself!
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");}
时间复杂度:
空间复杂度:
解法二:
It turns out we can do it in one-pass. While we iterate and inserting elements into the table, we also look back to check if current element’s complement already exists in the table. If it exists, we have found a solution and return immediately.
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");}
时间复杂度:
空间复杂度:
- 1. Two Sum && 167. Two Sum II
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1. Two Sum
- 1. Two Sum Ruby
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1.Two Sum
- anhularjs-路由。关于嵌入html页面
- Python3错误和异常
- (转)ScrollView中嵌套高德地图,触摸冲突解决
- 感知机学习算法
- smoj2084:种花(无汇源的可行流)
- 1. Two Sum
- Java 抽象类中变与不变的行为设计
- Django logging
- java冒泡排序
- let var const
- 数据库中随机查询 10条数据
- 远程连接阿里云ECS服务器For Windows
- Java中字符不变性
- (POj 2230)Watchcow [有向欧拉图] 输出欧拉回路