Two Sum III - Data structure design

LintCode Q 607 - 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.

Example:
add(1); add(3); add(5);
find(4) // return true
find(7) // return false

Solution

Code:

public class TwoSum {
	/ **
	  @param number: An integer
	  @return: nothing
	 * /
	
	private List<Integer> list;
	private Map<Integer, Integer> map;
	
	public TwoSum() {
		this.list = new ArrayList<>();
		this.map = new HashMap<>();
	}
	
	public void add(int number) {
		// write your code here
		if (map.containsKey(number)) {
			map.put(number, map.get(number) + 1);
		} else {
			list.add(number); map.put(number, 1);
		}
	}

	/ **
	  @param value: An integer
	  @return: Find if there exists any pair of numbers which sum is equal to the value.
	 * /
	public boolean find(int value) {
		// write your code here
		for (int i = 0; i < list.size(); i++) {
			int num1 = list.get(i), num2 = value - num1;
			if ( (num1 == num2 && map.get(num1) > 1) ||
			     (num1 != num2 && map.containsKey(num2)) )
				return true;
		}
		
		return false;
	}
}

   Reprint policy


《Two Sum III - Data structure design》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC