LeetCode – Two Sum (Java) —题解
来源:互联网 发布:基于java的oa审批流程 编辑:程序博客网 时间:2024/06/07 09:49
题干:
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.
For example:
Input: numbers={2, 7, 11, 15}, target=9Output: index1=1, index2=2
My First Try
This problem is pretty straightforward. We can simply examine every possible pair of numbers in this integer array.
Time complexity in worst case: O(n^2).
如我后来注释的那样,该方法并不能减小时间复杂度,可能只是筛选出了很小的一部分数据。在两个for循环中消耗了许多时间。
Better Solution
Use HashMap to store the target value.
Time complexity depends on the put and get operations of HashMap which is normally O(1).
Time complexity of this solution is O(n).
转载自:http://www.programcreek.com/2012/12/leetcode-solution-of-two-sum-in-java/
文章有改动。
- LeetCode – Two Sum (Java) —题解
- LeetCode题解:Two Sum
- LeetCode题解:Two Sum
- leetcode-Two Sum[题解]
- [LeetCode题解001]Two Sum
- LeetCode题解 || Two Sum问题
- LeetCode 1 Two Sum 题解
- [Leetcode题解]001 Two Sum
- 1. Two Sum : LeetCode 题解
- leetcode题解-1.Two Sum
- [LeetCode] Two Sum Python 题解
- leetcode 题解 1. Two Sum
- LeetCode 1 Two Sum题解
- 【LeetCode】Two Sum 题解报告
- LeetCode题解(1)--Two Sum
- LeetCode题解-1-Two Sum
- LeetCode题解 C++ Two Sum
- leetcode题解-1. Two Sum
- 第三次上机实践项目-项目3-小学生算数
- 设计模式-行为模式
- 存储过程与触发器
- 网关和子网掩码概念
- 你就可以在这项计划中
- LeetCode – Two Sum (Java) —题解
- (蓝桥杯)历届试题 蚂蚁感冒 (思维题)
- Map stack和Queue -java
- 转自一位学长的日志安排
- Leetcode 第一题 Two Sum java代码
- Java中@Override的作用
- Period (HDU_1358) KMP+循环节
- JavaWeb开发之十三:Javabean
- 单链表建环