leetcode:Two Sum 【Java】
来源:互联网 发布:linux查看当前路径 编辑:程序博客网 时间:2024/06/05 04:55
一、问题描述
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
二、问题分析
注意nums数组中可能存在重复元素(附录中程序无法解决该问题),例如nums = [0,2,3,0],target = 0,正确结果应该是[0,3]而不是[3,3].
三、算法代码
public class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();int gap = -1;Integer index;int [] result = new int[]{-1,-1};for(int i = 0; i <= nums.length - 1; i++){gap = target - nums[i];index = map.get(gap);if(index == null){map.put(nums[i], i);}else{result[0] = index;result[1] = i;break;}}return result; }}四、附录
public static int[] twoSum(int[] nums, int target) {HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();for(int i = 0; i <= nums.length - 1; i++){map.put(nums[i], i);}int [] result = new int[]{-1, -1};int first = -1;int second = -1;for(int j = 0; j <= target / 2; j++){first = j;second = target - j;if(map.containsKey(first) && map.containsKey(second)){result[0] = map.get(first);result[1] = map.get(second);break;}} return result; }
0 0
- LeetCode: Two Sum (Java)
- [Leetcode] Two Sum (Java)
- 【Leetcode】two sum JAVA
- LeetCode java Two Sum
- Two Sum leetcode Java
- [LeetCode][Java] Two Sum
- leetcode:Two Sum 【Java】
- LeetCode|Two Sum-java
- leetcode Two Sum(Java)
- LeetCode – Two Sum (Java)
- [LeetCode java] 1.Two Sum
- LeetCode(001) Two Sum (Java)
- LeetCode 1 Two sum Java
- [leetcode-1]Two Sum(java)
- LeetCode – Two Sum (Java)
- LeetCode 1 - Two Sum ( JAVA )
- LeetCode(java)1. Two Sum
- leetcode 1. Two Sum -----java
- 常用的linux命令
- HttpSession详解
- jdk和jre的区别
- hdu3829 二分匹配 最大独立集
- seoreZgniliarTlairotcaF.172
- leetcode:Two Sum 【Java】
- 解决Linux 下 root用户删除文件提示:Operation not permitted
- 第四章 第一节——效率本质
- oracle goldengate基础
- Spring boot app动态更新数据库表
- uva714 - Copying Books
- 深入研究java.lang.Class类
- Android系统input系统(1)
- uva607