leetcode 1. Two Sum
来源:互联网 发布:淘宝的全球购是正品吗 编辑:程序博客网 时间:2024/04/29 16:46
原题链接:1. Two Sum
【思路2-Java】
如果不借用 hashmap,直接用 brute force的话,时间复杂度为 O(n2)。我们可以先对 nums 数组进行排序,时间复杂度为O(nlogn),然后用两个指针start 和 end分别指向开头和结尾,在 start < end 范围内进行查找,有下列3中情况:
【思路1-Java】
借用 hashmap,时间复杂度可以降到 O(n),hashmap 中 key 为 nums 数组元素的值,value 为数组元素对应下标。假如对于第 i 个数 nums[i],如果 hashmap 中包含 target - nums[i]的 key 值,那么说明已经可以找到这样两个和为 target 的数,返回即可,否则,返回 null:
public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) if (hm.containsKey(target - nums[i])) return new int[]{hm.get(target - nums[i]), i}; else hm.put(nums[i], i); return null; }16 / 16 test cases passed. Runtime: 6 ms Your runtime beats 58.79% of javasubmissions.
【思路2-Java】
如果不借用 hashmap,直接用 brute force的话,时间复杂度为 O(n2)。我们可以先对 nums 数组进行排序,时间复杂度为O(nlogn),然后用两个指针start 和 end分别指向开头和结尾,在 start < end 范围内进行查找,有下列3中情况:
1. nums[start] + nums[end] = target,那么直接返回 start 和 end
2. nums[start] + nums[end] < target,那么 start++
3. nums[start] + nums[end] > target,那么 end--
如果没找到就返回 null。
但是我们要注意的是,不能直接对原数组进行排序,因为原数组被打乱了,那么原先的下标也就被打乱了,正确的做法是:申请一个同样大小的数组,然后将原数组拷贝到新的数组中,再对新数组进行排序,最后在原数组中找到这两个元素的下标即可:
public int[] twoSum(int[] nums, int target) { int[] sNums = new int[nums.length], res = null; System.arraycopy(nums,0,sNums,0,nums.length); Arrays.sort(sNums); int start = 0, end = nums.length - 1, index = 0; while(start < end) if (sNums[start] + sNums[end] == target) {res = new int[]{start, end}; break;} else if (sNums[start] + sNums[end] < target) start++; else end--; for (int i = 0; i < nums.length; i++) if (sNums[start] == nums[i] || sNums[end] == nums[i]) res[index++] = i; return res; }16 / 16 test cases passed. Runtime: 4 ms Your runtime beats 98.85% of javasubmissions.
欢迎优化!
1 0
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 【LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- leetcode 1. Two Sum
- [leetcode] 1. Two Sum
- leetcode 1. Two Sum
- Leetcode- 1. Two Sum
- LeetCode-1.Two Sum
- Leetcode 1. Two Sum
- iOS7.0.1的注释插件失效解决办法与相应的配置
- 实现按钮响应的几种方法
- 试一试这样0 0
- ubutun
- 今日学习心得之读取资源文件
- leetcode 1. Two Sum
- 黑马程序员——多线程代码实践及一些思考
- 数据结构【线性表(二)链表】项目之线性表的应用:表的自然连接
- 大学时光
- codeforce 582-A GCD Table
- HDU2090算菜价
- 30多条mysql语句级优化方法,千万级数据库记录查询轻松解决
- [Leetcode]Container With Most Water
- nyoj-34韩信点兵