LeetCode 1.Two Sum 解题报告
2016-02-18 17:23
387 查看
1. Two Sum
My SubmissionsQuestion
Total Accepted: 188053 Total
Submissions: 888224 Difficulty: Medium
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
Subscribe to see which companies asked this question
Show Tags
Show Similar Problems
Have you met this question in a real interview?
Yes
No
Discuss
《编程之美》上的一道原题,如果用暴力枚举的方法,时间复杂度将是n的平方。但是如果借助hash技术可以巧妙的将平方复杂度降级。
我的AC代码
public class TwoSum { public static void main(String[] args) { int[] a = { 2, 7, 11, 15 }; System.out.println(twoSum(a, 9)); } public static int[] twoSum(int[] nums, int target) { int[] result = new int[2]; int n2; Integer idx; Map<Integer, Integer> map = new HashMap<Integer, Integer>(nums.length); for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); } for (int i = 0; i < nums.length - 1; i++) { n2 = target - nums[i]; idx = map.get(n2); if(idx != null && idx > i){ result[0] = i; result[1] = idx; break; } } return result; } }
相关文章推荐
- 前端开发的基础知识点摘要
- [转] 四种常见的 POST 提交数据方式
- js图片预加载
- Fortran学习笔记(7)
- C# Yield
- QT “Timers can only be used with threads started with QThread”的解决办法~
- 修复VMware 下Ubuntu启动不了问题
- hrbust 哈理工oj 2026 势力较量【并查集】
- android中连接到指定wifi
- tomcat下webapps目录
- 关于build-tools位置不一致问题
- iOS的计步实现
- vim编辑器的基本使用
- 关于协议传值
- webkit的一些不为人知的高级属性
- 表单填写不完整提交按钮灰色,填写完整自动解除解禁+jQuery验证提示
- Java导出Excel
- memcached在linux安装
- Xcode引用C++头文件出现 Unknown type name 'namespace' 错误的解决方法
- 简析大数据的平台架构