LeetCode1: TwoSum
来源:互联网 发布:密松水电站 知乎 编辑:程序博客网 时间:2024/06/14 04:07
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
public class Solution { public int[] twoSum(int[] numbers, int target) { // Start typing your Java solution below // DO NOT write main() function for(int i=0, j=0; i < numbers.length; i++){ for(j=i+1; j < numbers.length; j++){ if(numbers[i] + numbers[j] == target) return new int[] {i+1, j+1}; } } return null; }}
O(n) Solution:
public class Solution { public int[] twoSum(int[] numbers, int target) { // Start typing your Java solution below // DO NOT write main() function HashMap<Integer, Integer> exist = new HashMap<Integer, Integer>(); int [] res = new int[2]; for(int i=0; i< numbers.length; i++){ exist.put(numbers[i], i); } for(int i=0; i< numbers.length; i++){ if(exist.get(target - numbers[i]) !=null){ res[0] = i+1; res[1] = exist.get(target-numbers[i])+1; if(res[0] > res[1]){ int tmp = res[0]; res[0] = res[1]; res[1] = tmp; } return res; } } return null; }}
------------------------------------------------------------------------------------------------------------------------------------------
LL's solution:
public class Solution { public int[] twoSum(int[] numbers, int target) { // Start typing your Java solution below // DO NOT write main() function int len = numbers.length; HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>(); int i; for(i = 0; i<len; i++) hash.put(numbers[i],i); for(i=0;i<len; i++){ int newTarget = target-numbers[i]; if(hash.containsKey(newTarget)) return new int[]{i+1,hash.get(newTarget)+1}; } return null; }}
- LeetCode1: TwoSum
- leetcode1 twosum
- leetcode1 : twosum
- LeetCode1 TwoSum
- Leetcode1 twosum
- leetcode1 || TwoSum
- LeetCode1-TwoSum
- LeetCode1 TwoSum Java
- LeetCode1.TwoSum(C)
- LeetCode1 TwoSum (java实现)
- leetcode1 TwoSum--java使用Hashtable实现
- leetcode1
- leetcode1
- leetcode1
- leetcode1
- Leetcode1
- twoSum
- TwoSum
- Malware Defender 温馨规则
- IOS风格的日期控件(Time picker)
- 实现快速排序算法
- 小学聚会,你摊上事了!你让我发现了微信的漏洞!这事不赖我!
- zoj 1383 Binary Numbers
- LeetCode1: TwoSum
- MIN_MATCH
- hdu 1070 milk
- android-cts-manual-r4.pdf
- 2D简单绘图---QT
- 实现直接选择排序算法
- Android权限之三共享UID和签名
- 比赛小结:处女CF赛#166
- 为Android扩展一个硬件模块