leetcode1 || TwoSum

 一.java beginer做的第一个leetcode||TwoSum

      先上自己写的算法,提交成功,runtime大概43ms.

        


二. 网上找的Hashtable的解法

       1.首先先介绍Java中的Hashtable的用法

       Java中的两个类:java.util.Hashtable 和java.util.HashMap。

       Hashtable和HashMap对象把一个key 和一个value结合起来,并用put() 方法把这(key,value)输入到表中。通过调用get()方法把key作为参数得到这个value。因为key和value必须是对象,所以原始类型(primitive types)必须通过运用诸如Integer(int)的方法转换成对象。  

        public V put(K key, V value)
              Maps the specified key to the specified value in this hashtable. Neither the key nor the value can be null. The value can be retrieved by calling                   the  get  method with a key that is equal to the original key.


   public V get(Object key)

        Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. More formally, if this map contains a               mapping from a key k to a value v such that (key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such                 mapping.)


       示例代码:      

        Hashtable<String, Integer> numbers= new Hashtable<String, Integer>();
         numbers.put("one", 1);
         numbers.put("two", 2);
         numbers.put("three", 3);

        To retrieve a number, use the following code:

         Integer n = numbers.get("two");
         if (n != null) {
             System.out.println("two = " + n);
         }

      2.具体代码:

         

             第一行:导入Hashtable类

              第6行:创建int[]类型实例变量result,新建对象,令result引用它。

                      第7行: 创建Hashtable类型实例变量nums,并指定key,value都为Integer类型的对象。

             第9~10行:把numbers数组中的元素作为key,value递增,挨个放入Hashtable中。若numbers数组有相同元素,不会重复放入。

            第11行:把本来的二重for循环遍历判断和是否为target,转变为在哈希表上查找n,节省了时间

            第12行:觉得n<i,不太好理解。可以带入一个简单的例子过一遍程序帮助理解。numbers={0,4,3,0}                                              target=0;

              

                         key(numbers[i])    value(i)

                           (0              ,          0     )

                           (4              ,          1     )

                           (3              ,           2     )

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值