[LeetCode] Two Sum
来源:互联网 发布:ubuntu install g 编辑:程序博客网 时间:2024/05/01 03:52
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
其实这样一来就打破了map里原数组的顺序, e.g [-3.4,3,90] target=0 的test case中就出错了。
还有就是map.put()的时机,e.g. [3,4,2,7] target=6, 我最开始是直接在for循环里初始就map.put(numbers[i],i)了。这样在后面的判断就成功了,于是
返回了两个[1,1], 而不是[2,3]. 后来还在考虑index大小的问题。
e.g. [0,4,3,0] 如果我们一开始就put进去,那么到第二个0的时候,map中的value是[0=4,4=2,3=3] 就覆盖掉之前的结果了. 所以最好是先判断,再存入.
public int[] twoSum(int[] numbers, int target) { int[] res=new int[2]; if(numbers.length==0) return res; HashMap<Integer, Integer> map= new HashMap<>(); for(int i=0;i<numbers.length;i++){ if(map.containsKey(target-numbers[i])){ res[0]=map.get(target-numbers[i])+1; res[1]=i+1; return res; } map.put(numbers[i],i); } return res; }
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- 谈谈开源技术选型
- 面向服务与微服务架构
- android Dialog
- xcode静态库,动态库的一些文章
- android Dialog
- [LeetCode] Two Sum
- AsyncTask
- 再谈xml
- android JSON
- ScrollView
- Documentation目录下的as-iosched.txt文档翻译
- 三色旗问题的解决
- JavaScript
- 模式识别与机器学习---读书笔记之多项式曲线拟合