。Leetcode170二つの数字III - データ構造の設計

デザインと、サポート業務を追加して検索するクラスの必要性をTwoSumクラスを実装すること。

追加-内部データ構造の数を追加します。
操作を見つける-整数内部データ構造のペアがあるかどうかを調べるために、2つの数の和が所定数に等しくなるようにします。

例1:

(1)追加します。(3)追加します。(5)追加します。
見つける(4) - >真
のfind(7) - >偽
示例2:

(3)追加します。(1)追加します。(2)追加。
(3)を見つける- >真
のfind(6) - >偽

順序付きリストにおいて、二重ポインタを使用することができる、時間はO(N)であり、時間の桁はO(N)であるインサート。

ハッシュテーブルは、挿入時間O(1)、O(N)の時間を見つけるために使用することができます。

どちらの方法空間はO(N)です。

要約すると、ソートに問題解決のリストをソートする必要はありません。

データ構造が、また、ハッシュテーブルの最善の使用を設計するとき。

import java.util.HashMap;

class TwoSum {
  private HashMap<Integer, Integer> countsMap;

  /** Initialize your data structure here. */
  public TwoSum() {
    countsMap = new HashMap<Integer, Integer>();
  }

  /** Add the number to an internal data structure.. */
  public void add(int number) {
    if (countsMap.containsKey(number))
      countsMap.replace(number, countsMap.get(number) + 1);
    else
      countsMap.put(number, 1);
  }

  /** Find if there exists any pair of numbers which sum is equal to the value. */
  public boolean find(int value) {
    for (Map.Entry<Integer, Integer> entry : countsMap.entrySet()) {
      int key = value - entry.getKey();
      if ((key == entry.getKey() && entry.getValue() > 1)
       || (key != entry.getKey() && countsMap.containsKey(key))) {
        return true;
      }
    }
    return false;
  }
}

/**
 * Your TwoSum object will be instantiated and called as such:
 * TwoSum obj = new TwoSum();
 * obj.add(number);
 * boolean param_2 = obj.find(value);
 */

 

公開された537元の記事 ウォンの賞賛10000 + ビュー131万+

おすすめ

転載: blog.csdn.net/hebtu666/article/details/104304423