调用 find 方法时,遍历哈希表 cnt,对于每个键 x,判断 value - x 是否也是哈希表 cnt 的键,如果是,判断 x 是否等于 value - x,如果不等,说明找到了一对和为 value 的数字,返回 true;如果等,判断 x 的出现次数是否大于 1,如果大于 1,说明找到了一对和为 value 的数字,返回 true;如果小于等于 1,说明没有找到一对和为 value 的数字,继续遍历哈希表 cnt,如果遍历结束都没有找到,返回 false。
时间复杂度:
add 方法的时间复杂度为 $O(1)$;
find 方法的时间复杂度为 $O(n)$。
空间复杂度 $O(n)$,其中 $n$ 为哈希表 cnt 的大小。
1 2 3 4 5 6 7 8 91011121314151617181920
classTwoSum:def__init__(self):self.cnt=defaultdict(int)defadd(self,number:int)->None:self.cnt[number]+=1deffind(self,value:int)->bool:forx,vinself.cnt.items():y=value-xifyinself.cntand(x!=yorv>1):returnTruereturnFalse# Your TwoSum object will be instantiated and called as such:# obj = TwoSum()# obj.add(number)# param_2 = obj.find(value)
classTwoSum{privateMap<Integer,Integer>cnt=newHashMap<>();publicTwoSum(){}publicvoidadd(intnumber){cnt.merge(number,1,Integer::sum);}publicbooleanfind(intvalue){for(vare:cnt.entrySet()){intx=e.getKey(),v=e.getValue();inty=value-x;if(cnt.containsKey(y)&&(x!=y||v>1)){returntrue;}}returnfalse;}}/** * Your TwoSum object will be instantiated and called as such: * TwoSum obj = new TwoSum(); * obj.add(number); * boolean param_2 = obj.find(value); */
classTwoSum{public:TwoSum(){}voidadd(intnumber){++cnt[number];}boolfind(intvalue){for(auto&[x,v]:cnt){longy=(long)value-x;if(cnt.contains(y)&&(x!=y||v>1)){returntrue;}}returnfalse;}private:unordered_map<int,int>cnt;};/** * Your TwoSum object will be instantiated and called as such: * TwoSum* obj = new TwoSum(); * obj->add(number); * bool param_2 = obj->find(value); */
typeTwoSumstruct{cntmap[int]int}funcConstructor()TwoSum{returnTwoSum{map[int]int{}}}func(this*TwoSum)Add(numberint){this.cnt[number]+=1}func(this*TwoSum)Find(valueint)bool{forx,v:=rangethis.cnt{y:=value-xif_,ok:=this.cnt[y];ok&&(x!=y||v>1){returntrue}}returnfalse}/** * Your TwoSum object will be instantiated and called as such: * obj := Constructor(); * obj.Add(number); * param_2 := obj.Find(value); */
1 2 3 4 5 6 7 8 910111213141516171819202122232425
classTwoSum{privatecnt:Map<number,number>=newMap();constructor(){}add(number:number):void{this.cnt.set(number,(this.cnt.get(number)||0)+1);}find(value:number):boolean{for(const[x,v]ofthis.cnt){consty=value-x;if(this.cnt.has(y)&&(x!==y||v>1)){returntrue;}}returnfalse;}}/** * Your TwoSum object will be instantiated and called as such: * var obj = new TwoSum() * obj.add(number) * var param_2 = obj.find(value) */