Two Sum
2015-06-10 20:56
225 查看
1. Question
给一整数数组,找两个数,使其和正好是给定值。函数 twoSum应当返回两个数的索引,且index1小于index2。索引不是从0开始的。假设每个输入都正好有一个解。
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. You may assume that each input would have exactly one solution. Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2
2. Solution
最优方案时间复杂度O(n)2.1 O(n2) solution
用两个循环遍历所有数对,找到符合要求的。2.2 O(nlogn) solution
方案一:采用二叉搜索
数组按升序排序(采用map存储数组值和索引)遍历数组,假设每个值是两个数的其中一个值,采用二叉搜索查找另一个值。
import java.util.Hashtable; public class Solution { //when using map structure, we don't need to sort the array public int[] twoSum( int[] numbers, int target ){ Hashtable< Integer, Integer > num = new Hashtable< Integer, Integer >(); for( int i=0; i< numbers.length; i++ ){ if( num.get( numbers[i]) == null ) num.put(numbers[i], i); Integer j = num.get( target - numbers[i]); if( j!=null && j < i ) return new int[] { j.intValue()+1, i+1 }; } return null; } }
map
相关文章推荐
- 06-图8. 关键活动
- CMSIS-RTOS RTX API创建一个线程的多个运行实例
- J8口管脚说明
- [android]APP启动界面——SplashActivity
- React学习——ListView(Reflux)
- J8口管脚说明
- Scala-List
- hadoop fs -put
- java 容器类研究一:HashMap源码原理分析
- [Python] 目录和文件操作
- 【BZOJ1026】【SCOI2009】windy数 数位DP
- lab4 Cache Geometries 深入理解计算机系统——高速缓存
- 微软100题(75)二叉树最低公共父节点
- Python 显示LinkedIn用户作业
- HDU 4287 Intelligent IME (字典树 && map)
- 解决Item控件抢占焦点
- 树莓派玩转WIN10之安装篇
- 关于MVC中Layout母版页文件
- 输入法框架
- MDT 2013 从入门到精通之自动化部署Windows 8.1