LeetCode - Two Sum
来源:互联网 发布:高级有限元分析软件 编辑:程序博客网 时间:2024/05/20 12:23
Question:
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
Answer:
import java.util.HashMap;public class TwoSum {public static void main(String[] args) {// TODO Auto-generated method stubint[] numbers = {2};int target = 18;int[] ret = twoSum(numbers, target);for (int i = 0; i < ret.length; i++) {System.out.println(ret[i]);}}public static int[] twoSum(int[] numbers, int target) {int length = numbers.length;// if (length < 2) {// return null;// }assert(length >= 2);int[] ret = new int[2];HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();for (int i = 0; i < length; i++) {if (!map.containsKey(numbers[i])) {map.put(target - numbers[i], i);}if (map.containsKey(numbers[i])) {int j = map.get(numbers[i]);if (j < i) {ret[0] = j + 1;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
- VMware技术大讲堂- vCAC快速部署应用
- VMware技术大讲堂-vSphere Replication
- 9 Android Client get 登录方式
- 黑马程程序员--javaSE--javaIO流
- 提取并生成文件夹下所有目录和文件名
- LeetCode - Two Sum
- DARPA慷慨解囊的背后:Python与大数据的火花
- iOS网络通信http之NSURLConnection
- 11-EL表达式判断值是否为空
- Java字符串——startWith endWith
- Web自动化测试中的接口测试
- sicily ISBN
- STM32 启动文件选择
- 【数据库】BAT文件登录MySQL及SQL查询命令精解