zoukankan      html  css  js  c++  java
  • 170. Two Sum III

    Design and implement a TwoSum class. It should support the following operations: add and find.

    add - Add the number to an internal data structure.
    find - Find if there exists any pair of numbers which sum is equal to the value.

    For example,

    add(1); add(3); add(5);
    find(4) -> true
    find(7) -> false

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


    此题是一个设计题,和之前的两个two sum题目不同的地方是,此题不是给数组,而是给了add,find方法,此题有个小细节需要考虑,实际操作中究竟是add的操作多还是find的操作多?因此对应了以下几种做法:
    1.add的操作多的时候,可以用hashmap来存储数据,key保存加的值,value保存同一个key值出现的次数。然后迭代哈希表键值来检查是否和等于指定值。
    代码如下:

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

    /** Add the number to an internal data structure.. */
      public void add(int number) {
        map.put(number,map.containsKey(number)?map.get(number)+1: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:map.entrySet()){
          int a = entry.getKey();
          int b = value-a;
          if((a==b&&map.get(a)>1)||a!=b&&map.containsKey(b)){
            return true;
          }
        }
        return false;
      }
    }

    2.接下来考虑find多的情况,即把add的数都两个两个加起来,存储到hashset里面,然而这么做相当于是用空间去换了时间,最后给出了TLE,该算法不可行。代码如下:

    public class TwoSum {
      Set<Integer> num;
      Set<Integer> sum;
    /** Initialize your data structure here. */
      public TwoSum() {
        num = new HashSet<Integer>();
        sum = new HashSet<Integer>();
      }

    /** Add the number to an internal data structure.. */
      public void add(int number) {
        if(!num.contains(number)){
          Iterator<Integer> iter = num.iterator();
          while(iter.hasNext()){
          sum.add(iter.next()+number);
          }
          num.add(number);
        }else{
          sum.add(2*number);
        }
      }

    /** Find if there exists any pair of numbers which sum is equal to the value. */
      public boolean find(int value) {
        return sum.contains(value);
      }
    }

    此题可以学到,hashset和hashmap都可以用iterator进行迭代(Iterator<Integer> iter = hashmap.keySet().iterator()),也可以手动对hashmap进行迭代,如Map.Entry<a,b> entry;以后还会有keySet(),valueSet()等等

  • 相关阅读:
    用C++做微信公众平台开发的后台开发时,用sha1加密验证的方法
    UART Receive FIFO and Receive Timeout
    Compile cpp File Manually without IDE under Mingw Environment
    html5 返回当前地理位置的坐标点(经纬度)
    逆袭!花两个月吃透这份“MySQL宝典”拿到字节offer
    MySQL约束的概述
    2020-11-28
    人工智能能力提升指导总结
    年轻就该多尝试,教你20小时Get一项新技能
    MySQL~存储过程基本操作
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6353768.html
Copyright © 2011-2022 走看看