zoukankan      html  css  js  c++  java
  • two sum class

     基本思路就是递归的把k sum化成k-1 sum,直到变成trivial的2sum来做。

    可以用两个hashset 存元素,sum ,这样就是store O(n), get(O(1))

    class TwoSum1 implements TwoSum{
        /**
         * Stores @param input in an internal data structure.
         */
        Map<Integer, Integer> storeMap = new HashMap<Integer, Integer>();
        public void store(int input) {
            //if the input value exists in the map
            if (storeMap.containsKey(input)) {
                storeMap.put(input, storeMap.get(input) + 1);
            } else {
                storeMap.put(input, 1);
            }
        }
    
        /**
         * Returns true if there is any pair of numbers in the internal data structure which
         * have sum @param val, and false otherwise.
         * For example, if the numbers 1, -2, 3, and 6 had been stored,
         * the method should return true for 4, -1, and 9, but false for 10, 5, and 0
         */
        public boolean test(int val) {
            for (Integer currVal : storeMap.keySet()) {
                Integer otherNumber = val - currVal;
                //if the map contains the other number
                if (storeMap.containsKey(otherNumber)) {
                    if (otherNumber.equals(currVal)) {
                        //If the number is the same as current, then check if another number exists
                        Integer count = storeMap.get(currVal);
                        //another same number exists
                        if (count > 1) {
                            return true;
                        }
                    } else {
                        return true;
                    }
                }
            }
            return false;
        }
    
        public static void main(String[] args) {
            TwoSum twoSum = new TwoSum();
            twoSum.store(1);
            twoSum.store(-2);
            twoSum.store(3);
            twoSum.store(6);
            twoSum.store(6);
    
            System.out.println("Test " + twoSum.test(4));
            System.out.println("Test " + twoSum.test(-1));
            System.out.println("Test " + twoSum.test(9));
            System.out.println("Test " + twoSum.test(12));
            System.out.println("Test " + twoSum.test(10));
            System.out.println("Test " + twoSum.test(5));
            System.out.println("Test " + twoSum.test(0));
        }
    }
    

      

  • 相关阅读:
    [Vue warn]: Duplicate keys detected: '1'. This may cause an update error
    【转载】 github vue 高星项目
    前端面试题目汇总摘录(JS 基础篇)
    微信小程序-滚动Tab选项卡
    日期格式与标准时间之间互转
    git rebse 操作失误回退到上一步
    js判断数组中某个值是否存在
    git 不区分文件名大小写 解决办法
    React + antd 实现动态表单添加删除功能
    leetcode 重排链表
  • 原文地址:https://www.cnblogs.com/apanda009/p/7945005.html
Copyright © 2011-2022 走看看