jiler的LeetCode学习笔记 java版本Two Sum
2015-03-13 23:06
387 查看
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
问题描述: 给你一系列整型值,找到其中的两个数,使他们相加等于给的target。函数结果返回两个数的位置。并且第一个下标比第二个小。注意,两个下标不是以0开始的。
问题是 复杂度,也就是效率。提示中给了可以使用HashMap。下面是我的代码,不当之处多多批评:
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
问题描述: 给你一系列整型值,找到其中的两个数,使他们相加等于给的target。函数结果返回两个数的位置。并且第一个下标比第二个小。注意,两个下标不是以0开始的。
问题是 复杂度,也就是效率。提示中给了可以使用HashMap。下面是我的代码,不当之处多多批评:
//思路1:两个for嵌套循环,时间超时 //思路2:一个循环数组,复杂度为o(n);总和减去这个,另一个在数组另存为的hashmap中查找,这样效率极高。 public int[] twoSum(int[] numbers, int target) { int[] index ={0,0}; int flag = 0; HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>(); for(int i=0;i<numbers.length;i++){ hm.put(numbers[i], i); } for(int j=0;j<numbers.length;j++){ Integer another = hm.get((target - numbers[j])); if(another != null && another != j ){ index[0]=j+1; index[1]=another+1; break; } } return index; }
相关文章推荐
- jiler的LeetCode学习笔记 java版本Longest Substring Without
- jiler的LeetCode学习笔记 java版本Median of Two Sorted Arra
- Java学习笔记(3)----网络套接字服务器多线程版本
- 看完think in java第8章后的想法以及对java 1.5以后版本泛型的学习笔记
- 31天重构学习笔记(java版本)
- java学习笔记 20171017 dynamic web module 更改为高版本失败
- Java学习笔记(二)之―Java基础, Java平台版本, JDK环境搭建
- LeetCode 学习笔记:Question 1、Two Sum
- leetcode 1 two sum 刷题学习笔记
- leetcode Reverse Integer java基本编程学习笔记(一)
- 我的Thinking in Java学习笔记(2)
- JAVA学习笔记之JIRA
- JAVAGUIDE(学习笔记1)
- 我的Thinking in Java学习笔记(七) (zt)
- Java中文处理学习笔记
- Thinking in Java学习笔记(2)(zt)
- 我的Thinking in Java学习笔记(八)
- 我的Thinking in Java学习笔记(四) (zt)
- Thinking in Java学习笔记(三)(zt)