[LeetCode]Two Sum
2016-09-12 16:41
381 查看
这道题目本身并不难,难点在于它是我做的第一道。在此我建议大家做leetecode最好不要用IDE,从实际出发考察自己。
这道题我提交了3次才通过,原因出在以下几点:
1、整型数组的创建需要指定长度。
对于:
也不允许:
正确的是:
2、对于整型数组的长度。
用惯了IDE,对于整形数组的长度获取是通过字段还是方法有模糊。
正确的是字段:
3、方法必须有个return。
我只在for循环内用了return,却忽略了这点。
不过对于更优解则是使用hashtable。这个我也想过,不过思考的比较肤浅就放弃了,有时候就是这么容易失之交臂。
这道题我提交了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"); }
相关文章推荐
- LeetCode(62)-Two Sum
- leetcode 1: 找出两个数相加等于给定数 two sum
- leetcode 刷题题解(c++) 1.Two Sum (hash表,排序+二分查找)
- [leetcode 1] Two Sum
- LeetCode 学习笔记:Question 1、Two Sum
- LeetCode 1.Two Sum
- Leetcode 1.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:1. Two Sum
- leetcode 1 Two Sum
- leetcode 1 Two Sum
- [leetcode 1] Two Sum
- Leetcode学习(1)—— Two Sum
- LeetCode:Algorith1 —Two Sum