[LeetCode]Two Sum
来源:互联网 发布:c 库存管理系统源码 编辑:程序博客网 时间:2024/04/29 06:42
这道题目本身并不难,难点在于它是我做的第一道。在此我建议大家做leetecode最好不要用IDE,从实际出发考察自己。
这道题我提交了3次才通过,原因出在以下几点:
1、整型数组的创建需要指定长度。
对于:int[] result;
是允许的,但是它只是创建了句柄,并没有开辟存储空间。
也不允许:int[] result=int[];
它没有指定长度。
正确的是:int[] result = new int[2];
2、对于整型数组的长度。
用惯了IDE,对于整形数组的长度获取是通过字段还是方法有模糊。
正确的是字段:int length = nums.length;
3、方法必须有个return。
我只在for循环内用了return,却忽略了这点。
不过对于更优解则是使用hashtable。这个我也想过,不过思考的比较肤浅就放弃了,有时候就是这么容易失之交臂。
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");}
0 0
- 【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
- servernet示例
- 金纳米棒
- Vim的分屏功能
- tomcat出现错误 org.apache.catalina.LifecycleException
- 微信公众号自定义菜单
- [LeetCode]Two Sum
- 时间小控件
- [HDU 5869] Different GCD Subarray Query (线段树GCD+离线算法) (好题)
- Cannot change version of project facet Dynamic Web Module to 2.3
- html5基于数据存储的评论&留言板demo
- 批处理基本语法整理(二)
- 过滤数组,用html5的filter一步搞定
- 善假于物也--PowerDesigner
- onSelectStart=return false