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
原创粉丝点击