LeetCode题解:Two Sum
来源:互联网 发布:淘宝代销分账怎么设置 编辑:程序博客网 时间:2024/06/05 20:12
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
题意:给定一个数组,找出其中两个元素的和为给定整数
解题思路:用HashMap建立数组元素与目标整数的差的映射,存在就是有
代码:
public class Solution { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < nums.length; i++){ if(map.containsKey(target - nums[i])){ result[0] = map.get(target - nums[i]); result[1] = i + 1; return result; }else{ map.put(nums[i], i + 1); } } return result; }}
0 0
- LeetCode题解:Two Sum
- LeetCode题解:Two Sum
- leetcode-Two Sum[题解]
- [LeetCode题解001]Two Sum
- LeetCode题解 || Two Sum问题
- LeetCode 1 Two Sum 题解
- [Leetcode题解]001 Two Sum
- 1. Two Sum : LeetCode 题解
- leetcode题解-1.Two Sum
- [LeetCode] Two Sum Python 题解
- leetcode 题解 1. Two Sum
- LeetCode 1 Two Sum题解
- 【LeetCode】Two Sum 题解报告
- LeetCode题解(1)--Two Sum
- LeetCode题解-1-Two Sum
- LeetCode题解 C++ Two Sum
- leetcode题解-1. Two Sum
- LeetCode 题解(55): Two Sum
- Redis HASH 操作类型封装
- ReactiveCocoa Documents 翻译(基于版本V2.5)
- Android Studio 9 patch 编译错误
- FTP命令字和响应码
- MongoDB 去重 分组(针对于某个field 或者 组合项的去重)
- LeetCode题解:Two Sum
- HDU2421Deciphering Password(数论&质因数分解)
- 【算法】【动态规划】Coin Exchange
- 0008 手动定制原版 Win7 操作系统(终)
- Ajax提高篇(2)DOM进行Web响应
- iOS开发-OC-类、对象、方法
- enum写法
- 关于VBS连接MySQL与连接Excel
- SQL语句中,为什么where子句不能使用列别名,而order by却可以?