Leetcode平台上的TwoSum题目用Java哈希表实现

上一篇 / 下一篇  2014-05-27 15:21:40 / 个人分类:学习

关于哈希表,大学里学过,但是实在没学进去。

然后自己好好搜索了一番,所谓的空间换时间,怎么换得呢?鄙人浅显的理解就是:元素和它的下标对调。
比如一个数组: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的详细介绍

http://wenku.baidu.com/link?url=j9dZ4WyIjzq4yxcpFZsNY6CZisNg6OPcgXlOpfaZ6KiDIuQc3K4h3B__HFJ3lRAvRy4F-YjZJZ98mew9NXviN48xknFBQLz1GaOF6CN6ERy

TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-04-26  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 17728
  • 日志数: 12
  • 建立时间: 2014-05-21
  • 更新时间: 2014-06-03

RSS订阅

Open Toolbar