博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java 哈希表运用-LeetCode 1 Two Sum
阅读量:4670 次
发布时间:2019-06-09

本文共 1128 字,大约阅读时间需要 3 分钟。

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

题意:给出无序数组A,找出两数之和等于目标数target

1.使用哈希表

2.转换思维,由两数之和转换成目标数与当前遍历数字的差

代码如下:

1 public class Solution { 2     public int[] twoSum(int[] nums, int target) { 3        Map
map = new HashMap
(); 4 int[] rs = new int[2]; 5 for (int i = 0; i < nums.length; ++i) { 6 int tmp = target - nums[i]; 7 if (map.get(tmp) == null) { 8 map.put(nums[i], i + 1); 9 }10 else {11 rs[0] = map.get(tmp);12 rs[1] = i + 1;13 break;14 }15 }16 17 return rs;18 }19 }

 

转载于:https://www.cnblogs.com/xlturing/p/4464993.html

你可能感兴趣的文章
Session History 属性和方法
查看>>
Others
查看>>
20172327 2018-2019-1 《程序设计与数据结构》第五周学习总结
查看>>
hdu 4284(状压dp)
查看>>
kafka资源
查看>>
XML Schema 配置文件自动生成c#类设计案例子
查看>>
数学公式字体样式大全
查看>>
1.pyhon入门
查看>>
解题:POI 2008 Station
查看>>
JAVA开发第一步——JDK 安装
查看>>
javascript 原生事件综合查询
查看>>
[视频]产品营销之拍出好电子产品,Peter Belanger是如何为苹果产品拍照的
查看>>
PAT 1019. General Palindromic Number
查看>>
[Leetcode] Sudoku Solver
查看>>
在web项目启动时,使用监听器来执行某个方法
查看>>
前端笔试题【1】--从字符串的第二个字符开始对数组进行排序
查看>>
html 标签总结
查看>>
netstat 查看端口
查看>>
tcp关闭连接:挥手讨论
查看>>
Game HDU - 5242 树链思想
查看>>