本文主要是介绍【LeetCode刷题】-- 170.两数之和III-数据结构设计,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
170.两数之和III-数据结构设计
方法:使用哈希表
class TwoSum {Map<Integer,Integer> map;public TwoSum() {map = new HashMap<>();}public void add(int number) {//key存元素,value为出现的次数map.put(number,map.getOrDefault(number,0) + 1);}public boolean find(int value) {//通过Map.entrySet遍历key和valuefor(Map.Entry<Integer,Integer> entry : map.entrySet()){int diff = value - entry.getKey();if(diff != entry.getKey()){if(map.containsKey(diff)){return true;}}//当前元素和差值相等,且当前元素出现次数大于1,返回trueelse{if( map.get(diff) > 1){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);*/
这篇关于【LeetCode刷题】-- 170.两数之和III-数据结构设计的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!