Leetcode平台上的TwoSum题目用Java哈希表实现
来源:互联网 发布:使用淘宝用户调查 编辑:程序博客网 时间:2024/05/16 08:59
关于哈希表,大学里学过,但是实在没学进去。
然后自己好好搜索了一番,所谓的空间换时间,怎么换得呢?鄙人浅显的理解就是:元素和它的下标对调。
比如一个数组:4,7,8,5,2
转到哈希就是:ht[4]=0, ht[7]=1, ht[8]=2, ht[5]=3, ht[2]=4.
但是鄙人也发现一个问题,如果数组元素是重复的,那么哈希表会有点问题啊,还在思考中...
Leetcode原题如下,如果粗暴用两层循环,平台一定会告诉我们:超时了。所以在各位前辈的指引下,用java hash实现了,源代码贴在题目后面了
然后自己好好搜索了一番,所谓的空间换时间,怎么换得呢?鄙人浅显的理解就是:元素和它的下标对调。
比如一个数组:4,7,8,5,2
转到哈希就是:ht[4]=0, ht[7]=1, ht[8]=2, ht[5]=3, ht[2]=4.
但是鄙人也发现一个问题,如果数组元素是重复的,那么哈希表会有点问题啊,还在思考中...
Leetcode原题如下,如果粗暴用两层循环,平台一定会告诉我们:超时了。所以在各位前辈的指引下,用java hash实现了,源代码贴在题目后面了
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
import java.util.Hashtable;public class Solution { public static int[] twoSum(int[] numbers, int target){ //int length = numbers.length; //System.out.println(length); Hashtable<Integer,Integer> ht = new Hashtable<Integer,Integer>(); int[] result = {0,0}; for(int i = 0; i < numbers.length; i++){ ht.put(numbers[i], i); } for(int i = 0; i < numbers.length; i++){ int gap = target - numbers[i]; if(ht.get(gap)!=null && ht.get(gap)>i){ result[0] = i + 1; result[1] = ht.get(gap) + 1; } } return result; }public static void main(String agrs[]){ int[] numbers = {0,4,3,0} ; int target = 0; int[] result = twoSum(numbers, target); System.out.println("index1="+result[0]+", index2="+result[1]); //index1=1, index2=2}}
百度文库里面有哈希JAVA的详细介绍
0 0
- Leetcode平台上的TwoSum题目用Java哈希表实现
- Leetcode平台上的Median of Two Sorted Arrays题目用Java快排实现
- Leetcode平台上的Median of Two Sorted Arrays题目用Java堆算法实现
- Leetcode OJ平台上的Binary Tree Preorder Traversal题目用java ArrayDeque实现
- [Leetcode]Test1 TwoSum [java]题目分析解答
- LeetCode OJ平台上Linked List Cycle题目用java快慢遍历实现
- LeetCode OJ平台上Binary Tree Postorder Traversal题目用java堆栈实现
- LeetCode OJ平台上的Climbing Stairs题目用java迭代解决
- LeetCode(二)关于TwoSum的实现
- LeetCode OJ平台上Binary Tree Inorder Traversal题目使用java堆栈方式实现
- C实现 LeetCode-> TwoSum
- LeetCode 算法实现:TwoSum
- Java-LeetCode-TwoSum
- [LeetCode-Java]1.TwoSum
- LeetCode/TwoSum Java
- leetcode之TwoSum[Java]
- 【Leetcode】TwoSum的解析
- leetcode-1-TwoSum 哈希表
- 最近课不怎么多 复习了下指针 感觉还不错
- Speaking Tips from Popular TED Talks
- 排列组合之全排列
- 关于linux重定向的解析
- 一本好书
- Leetcode平台上的TwoSum题目用Java哈希表实现
- DBI模块操作数据库示例
- ios开发中iphone模拟器中程序文件和数据库的存放位置
- String,StringBuffer和StringBuilder的异同
- 10.2形状类族的中的纯虚函数
- USB无线网卡的嵌入式Linux驱动移植 - 手记
- [beiwang]被忘记的vim命令
- jquery异步上传文件
- Perl and XS: Example 3: Set::Bit