日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

leetcode170. 两数之和 III - 数据结构设计

發布時間:2023/12/13 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode170. 两数之和 III - 数据结构设计 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

設計并實現一個?TwoSum 的類,使該類需要支持 add?和?find?的操作。

add?操作 -??對內部數據結構增加一個數。
find 操作 - 尋找內部數據結構中是否存在一對整數,使得兩數之和與給定的數相等。

示例?1:

add(1); add(3); add(5);
find(4) -> true
find(7) -> false
示例?2:

add(3); add(1); add(2);
find(3) -> true
find(6) -> false

在列表有序的情況下,可以使用雙指針,時間為O(N),插入一個數字的時間為O(N)。

可以使用哈希表,查找的時間為O(N),插入時間為O(1)。

兩種方法空間都是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);elsecountsMap.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);*/

?

總結

以上是生活随笔為你收集整理的leetcode170. 两数之和 III - 数据结构设计的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。