解题报告:#1 Two Sums
来源:互联网 发布:海关信息进出口数据 编辑:程序博客网 时间:2024/06/06 05:10
重回CSDN第一篇。解题报告中所说的注意点或难点仅针对我个人,未必对您适用,您可自行总结自己对一道题的注意点或难点
题目
Two Sums
Assumptions:
开始答题前先和面试官确认:
1. Is it possible that the given array has more than one solutions?
2. Do you want me to just find one solution or all solutions?
3. Any duplicated elements in the array (但跟这题没啥关系)?
4. Do we assume the array always have two or more elements? 如果YES的话一开始的边界情况就不用查啦。
思路一:
通过两个For循环找到两数和为Target时return两数的索引
注意点:
1. 边界情况 nums.length < 1 return null 要写
2. 第二个for loop 的index j 值从 i+1 开始算
解答:
public int[] twoSum(int[] nums, int target) { int[] ret = new int[2]; if (nums.length < 1) return null; for (int i = 0; i < nums.length; i++) { for (int j = i+1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { ret[0] = i; ret[1] = j; return ret; } } } return null; }
时复:O(n^2)
空复:O(1) 就定义了一个 int[] ret 变量而且这个array只有两个元素
思路二:
用哈希表 nums中的元素为Key ,每个元素的索引为Value 之循环原数组一次得到解
假如有符合的,把values拿出来赋给Int[]得解,假如没有符合的,push 元素到哈希表直到走完数组为止
注意点:
1. Java中HashMap的声明语法 (两年没写Java所以有点生)
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
2. 得值 往map里加东西 containsKey
map.get(key)
map.put(key, value)
map.containsKey(key)
解答:
public int[] twoSum(int[] nums, int target) { int[] ret = new int[2]; if (nums.length < 1) return null; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(target - nums[i])) { ret[0] = map.get(target - nums[i]); ret[1] = i; return ret; } map.put(nums[i], i); } return null; }
时复:O(n) 只遍历一遍数组
空复:O(n) HashMap的空间复杂度
- 解题报告:#1 Two Sums
- USACO :Subset Sums 解题报告
- LeetCode Algorithms No.1 Two Sums解题思路
- Leetcode (1) Two Sum 解题报告
- LeetCode(1) Two Sum解题报告
- Two Sum解题报告
- 解题报告:Two Sum
- leetcode 1:Two Sums
- HOJ 1401Gigantic Sums 解题报告
- LeetCode 解题报告 Two Sum
- LeetCode-Two Sum-解题报告
- Two Sum问题解题报告
- [LeetCode] Two Sum 解题报告
- 【LeetCode】Two Sum 解题报告
- LeetCode OJ 第1题 Two Sum 解题报告
- [leetcode] 373. Find K Pairs with Smallest Sums 解题报告
- [Leetcode] 373. Find K Pairs with Smallest Sums 解题报告
- pku 树形dp 1849 two 解题报告
- 初入Android
- WUST 1947 联络员(最小生成树+部分连好的点)
- 不能根据方法返回值来确认是否方法重载(Overload)
- dao模式
- VMWare Network Adapter VMnet1/8
- 解题报告:#1 Two Sums
- Linux更改网卡逻辑名称
- 元真先生:细数那些不利于健康的风水陷阱!
- UML学习
- iptables配置规则
- 刷题:设计一个类不能被继承
- xgboost和lightgbm学习
- zookeeper常用命令
- 威尔逊定理,费马小定理,欧拉定理