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

    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


    设计一个two sum 的类。包含add和find两种操作方式。

    1、使用HashMap和HashSet实现。

    public class TwoSum {
        
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        Set<Integer> set = new HashSet<Integer>();
        // Add the number to an internal data structure.
        public void add(int number) {
            if (set.contains(number)){
                map.put(number, 2);
            }else {
                set.add(number);
                map.put(number, 1);
            }
        }
    
        // Find if there exists any pair of numbers which sum is equal to the value.
        public boolean find(int value) {
            for (int num : set){
                if (num == value - num){
                    if (map.get(num) == 2){
                        return true;
                    }
                } else if (set.contains(value - num)){
                    return true;
                }
            }
            return false;
        }
    }
    
    
    // Your TwoSum object will be instantiated and called as such:
    // TwoSum twoSum = new TwoSum();
    // twoSum.add(number);
    // twoSum.find(value);

    2、使用HashMap 和 List(也可以只使用一个HashMap,记录一或者2即可。)

    public class TwoSum {
        
        private List<Integer> list = new ArrayList<Integer>();
        private Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    
        // Add the number to an internal data structure.
        public void add(int number) {
            if (map.containsKey(number)) map.put(number, map.get(number) + 1);
            else {
                map.put(number, 1);
                list.add(number);
            }
        }
    
        // Find if there exists any pair of numbers which sum is equal to the value.
        public boolean find(int value) {
            for (int i = 0; i < list.size(); i++){
                int num1 = list.get(i), num2 = value - num1;
                if ((num1 == num2 && map.get(num1) > 1) || (num1 != num2 && map.containsKey(num2))) return true;
            }
            return false;
        }
    }
    
    
    // Your TwoSum object will be instantiated and called as such:
    // TwoSum twoSum = new TwoSum();
    // twoSum.add(number);
    // twoSum.find(value);

    3、为什么要使用一个List,因为在遍历操作的时候,List要比Map或者Set快得多,使用一个List可以用空间换取时间。

  • 相关阅读:
    Java基础教程
    一个RDBMS左连接SQL执行计划解析
    hive时间日期函数及典型场景应用
    ETL数据采集方法
    数据仓库保存历史数据方法之拉链表
    NAS服务器局域网内IPad、手机、电视盒子等联网播放
    转:主流数据恢复软件——EasyRecovery/Ashampoo Undeleter/Wise Data Recovery/Recuva/Undelete 360
    [转]office2010一直卡在“正在受保护的视图中打开”
    [转]PROE传动链条的装配教程
    linux下svn定时更新项目
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6118658.html
Copyright © 2011-2022 走看看