[LeetCode]Two Sum
来源:互联网 发布:高斯混合聚类算法 编辑:程序博客网 时间:2024/05/21 06:28
题目描述
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
解题思路
- O(n*m)。两次for循环,找到numbers[i] + numbers[j] = target。时间肯定超时
- O(nlogn)。排序,然后两个指针一前一后遍历。因为题中说明了只有一对答案,因此不需要考虑重复的情况。
- O(n)。哈希表。将每个数字放在map中,历遍数组,如果出现和数组中的某一个值相加为target的时候,break。(本思路来自网上帖子)
代码
这里列出思路2和思路3的代码
思路2:
public int[] twoSum(int[] numbers, int target) { int start = 0,end = numbers.length - 1; int x,y;List<Node> list = new ArrayList<Node>();for(int i = 0;i < numbers.length;i++){Node node = new Node(numbers[i],i);list.add(node);}Collections.sort(list, new NodeComparator());while(start < end){x = list.get(start).value;y = list.get(end).value; if(y > target - x){ end--; } else if(x < target - y){ start++; } else { break; }}int p1 = list.get(start).pos+1;int p2 = list.get(end).pos+1;return new int[]{p1>p2?p2:p1,p1>p2?p1:p2};}
public class Node {int value;int pos;Node() {value = 0;pos = 0;}Node(int a, int b) {value = a;pos = b;}}
比较接口。
public class NodeComparator implements Comparator<Node>{@Overridepublic int compare(Node o1, Node o2) {// TODO Auto-generated method stubif(o1.value > o2.value){return 1;} else if(o1.value < o2.value){return -1;}return 0;}}
思路3:
public int[] twoSum(int[] numbers, int target) { int len = numbers.length; assert(len >= 2); int[] ret = new int[2]; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < len; i++){ if( !map.containsKey(numbers[i]) ){ map.put(target - numbers[i], i); // save another number } if( map.containsKey(numbers[i]) ){ // check is another number int idx = map.get(numbers[i]); if(idx < i){ ret[0] = idx + 1; // +1 for not zero-based ret[1] = i + 1; } } } return ret; }
0 0
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- android应用开发过程中更换资源文件不刷新(显示旧资源文件)问题
- mysql高可用探究(三)Lvs+Keepalived+Mysql单点写入读负载均衡主主同步高可用方案
- 解析url地址字串,获得请求参数
- 阿里巴巴2014笔试题(客户端)
- easyui的datagrid数据问题
- [LeetCode]Two Sum
- 入选CSDN社区周刊的内容标准
- linux diff详解
- mysql高可用探究(四)Heartbeat高可用Mysql主主同步方案
- 网站原创文章黄金法则:不要数量要质量。
- 单词全排列
- 『ZIP』检测zip文件的完整性
- SPI DMA 的使用
- VS2010中的C++0x特性 以后有时间在看