twoSum
来源:互联网 发布:vb6.0连接mysql数据库 编辑:程序博客网 时间:2024/05/17 01:34
给出一组数值,找出其中两个数之和等于给定的数值, 时间复杂度 O(n),空间复杂度 O(n),这样就不能用暴力方法一个一个代入了,时间复杂度为O(n),多数为哈希表
import java.util.Hashtable;public class Demo2 {public static void main(String args[]) {int[] a = { 2, 3, 1, 5, 7, 12, 32, 121 };int value = 34;for (int i : a)System.out.print(i + " ");twoSum(a, value);}public static void twoSum(int[] a, int value) {Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>();for (int i = 0; i < a.length; i++) {ht.put(a[i], i + 1);/** * HashTable的好处就在于可以指定key和value的映射关系 * 本例中关系如下: key 2, 3, 1, 5, 7, 12, 32, 121 * value 1,2,3,4,5,6.... * * */}for (int i = 0; i < a.length; i++) {int index1 = i + 1;if (ht.containsKey(value - a[i])) {int index2 = ht.get(value - a[i]);System.out.println("\n集合中满足合为" + value + "的元素下标为: " + index1+ " 和 " + index2);break;}}}}
0 0
- twoSum
- TwoSum
- TwoSum
- TwoSum
- twoSum
- TwoSum
- TwoSum
- TwoSum
- TwoSum
- TwoSum
- twoSum
- TwoSum
- twoSum
- TwoSum
- TwoSum
- twosum
- TwoSum
- TwoSum
- nyoj 14 会场安排问题
- 厄密多项式的实现
- 常用字符串hash算法
- Android学习笔记-App多线程下载模块实现(仿爱奇艺App)
- python中disutils打包与安装
- twoSum
- 学习链接收藏
- 初学nodejs 之 nodejs操作mysql
- 毕业好难
- hadoop
- 去除或替换listview 默认的点击选中时的颜色
- 毕业设计
- 网页开发之如何防止表单重复提交
- 4种简单的echo server——简单阻塞型,多进程,多线程,epoll