170. Two Sum III – Data structure design

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

思路: 题目不难,用个hashmap来解,注意可能会出现重复数字. hashMap中村数字跟出现的次数,
复杂度: 插入O(n), 查找O(1)

public class TwoSum {
    HashMap<Integer, Integer> map;

    public TwoSum (){
        map = new HashMap<>();
    }

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

    // Find if there exists any pair of numbers which sum is equal to the value.
    public boolean find(int value) {
        for (int key: map.keySet()) {
            int target = value - key;
            if (key == target && map.get(target) > 1) {
                return true;
            } else if (key != target && map.containsKey(target)) {
                return true;
            }
        }
        return false;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s