Two Sum Java
来源:互联网 发布:c语言和汇编语言的优点 编辑:程序博客网 时间:2024/05/22 17: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
Better Approach:
Key to solve: HashMap AC 432ms
Trade off between time and space,
Use Map(key: number, value: index)
number1+number2=target => target-number1=number2;
Time: O(n)
public class Solution { public int[] twoSum(int[] numbers, int target) { 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])){ //find target res[0]=map.get(numbers[i])+1; res[1]=i+1; break; }else{ map.put(target-numbers[i],i); } } return res; }}
0 0
- LeetCode: Two Sum (Java)
- [Leetcode] Two Sum (Java)
- Two Sum Java
- 【Leetcode】two sum JAVA
- Two Sum (Java)
- LeetCode java Two Sum
- Two Sum leetcode Java
- [LeetCode][Java] Two Sum
- [letecode java]Two Sum
- leetcode:Two Sum 【Java】
- Two Sum(Java)
- Two Sum(java)
- java-two sum
- LeetCode|Two Sum-java
- leetcode Two Sum(Java)
- LeetCode – Two Sum (Java)
- [LeetCode java] 1.Two Sum
- LeetCode(001) Two Sum (Java)
- androidpn-通信机制
- C# TcpClient 由于目标机器积极拒绝,无法连接
- daemon not running的解决办法
- 试用 Tomcat7.x 与 Tomcat6.x 的明显不同 + Context 填写方法 + 默认应用配置方法(转自ShaneLooLi)
- java中HashMap详解
- Two Sum Java
- MFC消息映射机制
- 数据挖掘分类方法探究----朴素贝叶斯方法
- androidpn-服务器介绍
- HDU 4961 Boring Sum(构造题)
- html与jsp互相传值示例
- 这篇文章主要介绍了ASP.NET自动为URL加上超链接的代码
- Java中用浮点型数据Float和Double进行精确计算时的精度问题
- kmp