LeetCode – Two Sum (Java) —题解
2016-03-19 20:31
489 查看
题干:
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:
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/
文章有改动。
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=9 Output: 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/
文章有改动。
相关文章推荐
- JavaWeb开发之十四:JavaWeb两种开发模式
- JavaWeb开发之十三:Javabean
- Java中@Override的作用
- Leetcode 第一题 Two Sum java代码
- Java面对对象入门
- eclipse的两个不同程序并排摆放,便于查看
- Java基础之异常篇
- 从零开始创建一个简单的springMVC工程(包含一些异常的解决方法)
- Java中的异常
- JavaWeb开发之十二:JSP九大内置对象
- 搭建spring开发环境
- 【JAVA】43、编写一个简易录入系统
- JavaWeb开发之十一:JSP基础语法
- 【JAVA】42、实例讲解——类设计分析
- Retrofit结合RxJava使用说明
- 20145227 《Java程序设计》第3周学习总结
- [置顶] Java 图形界面开发--图文并茂建立学生管理系统
- Java 图形界面开发--图文并茂建立学生管理系统
- java学习笔记(一)
- 【Java算法学习笔记】数组元素循环右移问题