zoukankan      html  css  js  c++  java
  • LeetCode:(Array-1)Two Sum 和HashMap以及HashTable等知识

    /*
     * Two Sum 
     * 
     * 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
    */

     思路:

    思路1:对于每一个元素,遍历寻找另一个元素使得和为target,时间复杂度O(n^2)。

    思路2:先排序,然后首尾两个指针向中间靠拢,两指针所指元素大于target,移动尾指针,小于target移动头指针,直至找到结果或者两个指针相遇。

      时间复杂度O(nlogn)。此方法可推广值3Sum,4Sum等。

      但是在这个题目中,排序后会改变元素的下标,所以不太可取。

    思路3:利用hashmap,将每个元素值作为key,数组索引作为value存入hashmap,然后遍历数组元素,在hashmap中寻找与之和为target的元素。

      ·时间复杂度O(n),空间复杂度O(n)。

    hashmap 和 hashTable的区别:

    1. hashmap是单线程的,不安全,hashtable是多线程的安全

    2. hashmap可以允许 值和键为空, hashtable不允许。

    在下面的代码中,用的是hashtable,有点不太合适,可以改为hashmap。

    Java代码: 

     1 package com.hb.leetcode;
     2 
     3 import java.util.Hashtable;
     4 
     5 import offer.utilities.ArrayUtils;
     6 
     7 
     8 /*
     9  * Two Sum 
    10 */
    11 public class TwoSum {
    12     public int[] twoSum(int[] numbers, int target) {        
    13         int[]  result = new int[2];
    14         //放数组值 和 下标
    15         Hashtable<Integer, Integer>  numstable = new Hashtable<Integer, Integer>();
    16         
    17         for(int i = 0 ; i < numbers.length ; i++){
    18             //对没一个数边放边查找
    19             if(numstable.get(target - numbers[i]) != null){
    20                 result[0] = numstable.get(target - numbers[i]) + 1;
    21                 result[1] = i + 1;
    22                 
    23             }else{
    24                 numstable.put(numbers[i], i);
    25             }   
    26         }        
    27         return result;
    28     }
    29     
    30     public static void main(String[] args) {
    31         int numbers[] = {3,4,2};
    32         int target = 6 ;
    33         TwoSum  test = new TwoSum();
    34         int indices[] = test.twoSum(numbers, target);
    35         ArrayUtils.printArray(indices);
    36     }
    38 
    39 }
  • 相关阅读:
    oracle sql日期比较
    rlwrap真是一个好东西
    Dataguard 归档丢失处理
    oracle latch工作原理
    Latch free等待事件
    Redhat Enterprise Linux 5 安装 Oracle 10g release 2
    oracle 日期问题
    Oracle自动存储管理 ASMLib的支持变化
    [官方文档] oracle官方文档总汇(9i,10g,11gR1, 11gR2)
    实时分布式搜索引擎比较(senseidb、Solr、elasticsearch)
  • 原文地址:https://www.cnblogs.com/Mokaffe/p/4346869.html
Copyright © 2011-2022 走看看