LeetCode/TwoSum Java
来源:互联网 发布:c 游戏编程 编辑:程序博客网 时间:2024/06/05 20:39
题目: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, and you may not use the same element twice.
题意:给个整数数组,返回两个数的索引如果如果这两个数相加等于一个指定的数,且不能使用同一个数两次,且输入将得到唯一的答案,即只会有一个结果。
思想:
1.采用Java中的HashMap遍历整个数组。
2.put(key,value):将数组放入HashMap中。
3.get(key):根据键得到相关的值。
4.注意:不能使用同一个元素两次!!!(如输入(3,3),如果不保证索引不相同,返回的值将为(0,0))。
这里写代码片package www.hugo.com;import java.util.HashMap;public class TwoSum { public int[] twoSum(int a[],int target){ HashMap <Integer,Integer> map = new HashMap<Integer,Integer>();//创建一个HashMap for(int i = 0;i < a.length;i++){ map.put(a[i],i);//将数组放入hashMap中,key=a[i] vaule=i; int two[] = new int[2];//一个存储满足条件的两个数的索引的数组 for(int i = 0;i<a.length;i++){ if(map.containsKey(target-a[i])&&(map.get(target-a[i])!=i)){//Attention:1.map.containsKey(target-a[i]):表示判断是否hash表里面有一个值等于(target-a[i]),若有则返回true. 2.(map.get(target-a[i])!=i):表示判断是否是同一个数!!hash于上面put()是以值-索引的方式放入hashMap中的,由于get方法是通过键得到值,所以get得到的顺其自然是索引。 two[0] = i; two[1] = map.get(target-a[i]); break; } } return two; }}
0 0
- Java-LeetCode-TwoSum
- [LeetCode-Java]1.TwoSum
- LeetCode/TwoSum Java
- leetcode之TwoSum[Java]
- [leetcode]-twoSum
- [leetcode]twoSum
- LeetCode-TwoSum
- 【Leetcode】TwoSum
- LeetCode - TwoSum
- leetcode :twoSum
- leetcode TwoSum
- leetcode twosum
- leetcode--twoSum
- LeetCode twoSum
- LeetCode-TwoSum
- leetcode--twoSum
- leetcode TwoSum
- TwoSum leetcode
- 天猫,京东各大网站锚点的跳转
- 用户管理
- mysql问题:1、本地连接不了mysql服务器,连接3306端口失败
- pycharm 汉化
- 51nod_1134 最长递增子序列(O(n*logn))
- LeetCode/TwoSum Java
- k8s集群部署DNS服务发现
- 30天自制操作系统(笔记1)
- 工具:GitHub入门
- 获取MySql每一列的数据类型和长度默认值等信息
- 大数据问题(九章算法)
- android组件之DrawerLayout(抽屉导航)-- 侧滑菜单效果
- 多渠道打包
- 点击空白处关闭弹出层