Leetcode - Two Sum III - Data Structure Design

[分析]
find的version1 版本注意num2Occur 需定义为Integer类型,建议version2版本

[ref]
https://leetcode.com/discuss/19515/my-solutions-java-and-python-time-for-add-time-for-find-space

public class TwoSum {
    private HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
	public void add(int number) {
	    map.put(number, map.containsKey(number) ? 2 : 1);
	}
	// version 2
    public boolean find(int value) {
	    for (Integer num1 : map.keySet()) {
	        int num2 = value - num1;
	        if (map.containsKey(num2) && (map.get(num2) == 2 || num1 != num2))
	            return true;
	    }
	    return false;
	}
	
    // version 1
	public boolean find1(int value) {
	    for (Integer num1 : map.keySet()) {
	        Integer num2Occur = map.get(value - num1);
	        if (num2Occur != null && (num2Occur == 2 || num1 != (value - num1)))
	            return true;
	    }
	    return false;
	}
}

// Version 1: TLE
// public class TwoSum {
//     private HashSet<Integer> sumSet;
//     private HashSet<Integer> numSet;
//     public TwoSum() {
//         sumSet = new HashSet<Integer>();
//         numSet = new HashSet<Integer>();
//     }
// 	public void add(int number) {
// 	    if (!numSet.isEmpty()) {
// 	        for (int item : numSet)
// 	            sumSet.add(item + number);
// 	    }
// 	    numSet.add(number);
// 	}

// 	public boolean find(int value) {
// 	    return sumSet.contains(value);
// 	}
// }

你可能感兴趣的:(Leetcode - Two Sum III - Data Structure Design)