Two Sum
来源:互联网 发布:网络电视老是卡怎么办 编辑:程序博客网 时间:2024/04/28 07:35
Two Sum
AC Rate: 592/2417
My SubmissionsGiven 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
这题选择了用HashMap来存储已经遍历过的元素,HashMap的对应关系是Value为元素下标,Key则是target与Value下标对应元素之差。
也就是说,每遍历一个元素,就看,map里有没有与它加和为target的key:
1.有。正在遍历的下标和map里存的下标,刚好就是所求。
2.没有。把这个元素所需的元素-本身的下标存进去。
HashMap的好处就是search的复杂度为O(1) :D
public class Solution { public int[] twoSum(int[] numbers, int target) { // Start typing your Java solution below // DO NOT write main() function int res[] = new int[2]; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i<numbers.length; i++) { if(!map.containsKey(numbers[i])) map.put(target - numbers[i],i); else { int idx = map.get(numbers[i]); if(idx < i) { res[0] = idx + 1; res[1] = i + 1; break; } } } return res; }}
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Responder一点也不神秘————iOS用户响应者链完全剖析
- 在从用户态到内核态的切换过程中,Linux主要做的事情
- esp寄存器与ebp寄存器介绍
- 从用户态向内核态切换的三种情况
- Linux用户态切换内核态介绍
- Two Sum
- Thinkpad E430+CentOS 6.4+ linux-3.10.12内核网卡驱动(无线+有线)配置
- PSoC中断
- 淘宝css注解
- vm使用技巧(未完)
- 佛挡杀佛第三方的身份
- 求一个序列的子序列个数(序列元素是一个字符)
- Qt下使用GDB远程调试ARM板
- Windows 7-64位上编译webkit源码纪实