首页 > 其他 > 详细

two sum class

时间:2017-12-02 10:37:43      阅读:206      评论:0      收藏:0      [点我收藏+]

 

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));
    }
}

  

two sum class

原文:http://www.cnblogs.com/apanda009/p/7945005.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!