Two Sum
2016-04-27 17:25
120 查看
题目描述:
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].
2种做法,第一种先排序,然后用双指针,一个在前,一个在后,一起往中间靠拢,时间复杂度O(n*logn)(注意:这里排序的话就把位置打乱了,所以要用Pair来记住位置);第二种牺牲空间换时间,采用hashmap,时间复杂度O(n)。
第一种做法:
第二种做法:
这里的n!=null&&n
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].
2种做法,第一种先排序,然后用双指针,一个在前,一个在后,一起往中间靠拢,时间复杂度O(n*logn)(注意:这里排序的话就把位置打乱了,所以要用Pair来记住位置);第二种牺牲空间换时间,采用hashmap,时间复杂度O(n)。
第一种做法:
class Pair implements Comparable<Pair>{ private int val; private int index; public int getVal() { return val; } public int getIndex() { return index; } public Pair(int val, int index) { super(); this.val = val; this.index = index; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub if(this.val>o.val) return 1; else if(this.val<o.val) return -1; return 0; } } public int[] twoSum(int[] nums, int target) { Pair[] pairs=new Pair[nums.length]; for (int i = 0; i < nums.length; i++) { pairs[i]=new Pair(nums[i], i+1); } int[] a=new int[2]; int i=0,j=pairs.length-1; Arrays.sort(pairs); while(i<j){ if(pairs[i].getVal()+pairs[j].getVal()==target){ a[0]=pairs[i].getIndex();a[1]=pairs[j].getIndex();return a; }else if(pairs[i].getVal()+pairs[j].getVal()<target){ i++; }else{ j--; } } return null; }
第二种做法:
public int[] twoSum(int[] nums, int target) { int[] a=new int[2]; HashMap<Integer, Integer> map=new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { Integer val=map.get(nums[i]); if(val==null) map.put(nums[i], i); Integer n=map.get(target-nums[i]); if(n!=null&&n<i){ a[0]=i; a[1]=n; return a; } } return null; }
这里的n!=null&&n
相关文章推荐
- 解决JQUERY ajax异步
- YII加载机制扩展冲突解决方案
- Android 编程下 Touch 事件的分发和消费机制
- web常用方法总结
- 中英文混合正则
- php接收数据流
- windows下wnmp搭建教程
- memcache 不稳定问题
- 手机正则和邮箱正则
- 基于scikit-learn(sklearn)做分类--3.优化--保存模型
- 值传递和值引用却别以及测试用例
- php程序员必知的基础~个人总结欢迎…
- 折半插入排序
- php调试工具之firephp
- selenium学习笔记(selenium IDE下载安装)
- Kafka学习(五):Kafka的消费编程模型
- ORA-01843: not a valid month
- ThinkPHP无法add保存数据
- Json-lib
- IntelliJ IDEA 使用svn时遇到的问题总结