码迷,mamicode.com
首页 > 其他好文 > 详细

two sum class

时间:2017-12-02 11:22:11      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:hashmap   ati   shm   bsp   numbers   another   for   eth   str   

 

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

标签:hashmap   ati   shm   bsp   numbers   another   for   eth   str   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!