【LeetCode】001.Two Sum
来源:互联网 发布:飞天侠淘宝客演示 编辑:程序博客网 时间:2024/06/08 07:40
题目:
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
遍历数组,直到找到满足要求的值。为了提高查询速度,用LinkedHashMap,这样只需遍历1次,而且不用回溯。细节之处是注意重复值的情况。
代码:
import java.util.*;public class Solution { public int[] twoSum(int[] nums, int target) {Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();// store duplicate valuesMap<Integer, Integer> map2 = new LinkedHashMap<Integer, Integer>();for (int i = 0; i < nums.length; i++) {if (map.containsKey(nums[i]))map2.put(nums[i], i + 1);elsemap.put(nums[i], i + 1);}int index1 = 0, index2 = 0;for (int i : map.keySet()) {index1 = map.get(i);if (i == target - i) {if (map2.containsKey(target - i)) {index2 = map2.get(target - i);break;}} else if (map.containsKey(target - i)) {index2 = map.get(target - i);break;}}return new int[] { index1, index2 };}}
0 0
- LeetCode 001. Two Sum
- 【LeetCode】001.Two Sum
- leetcode--001. Two Sum
- 【LeetCode】 001. Two Sum
- 【LeetCode】001. Two Sum
- [Leetcode.python] 001. Two Sum
- Leetcode Algorithm 001. Two Sum
- 【Leetcode】Two Sum (Sum)
- [LeetCode 解题报告]001.Two 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
- iOS开发之 UI 编程——第一讲
- Storm trident state
- MyBatis的动态SQL详解
- VC2010下Qt5的中文乱码问题
- C++构造函数
- 【LeetCode】001.Two Sum
- OC小游戏-人机大战-猜拳
- 欢迎使用CSDN-markdown编辑器
- Storm Trident 示例
- 例题2.2 数三角形 UVa11401
- 一步步学习Linux多任务编程
- 汉子乱码
- su与sudo su之间的区别
- ffmpeg 配置