Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

170. Two Sum III - Data structure design #127

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

public class TwoSum { List list = new ArrayList();

// Add the number to an internal data structure.
public void add(int number) {
    list.add(number);
}

// Find if there exists any pair of numbers which sum is equal to the value.
public boolean find(int value) {
    HashSet<Integer> set = new HashSet<Integer>();
    for(int i = 0; i < list.size(); i++) {
        if(set.contains(value - list.get(i))) {
            return true;
        }
        set.add(list.get(i));
    }
    return false;
}

}

// Your TwoSum object will be instantiated and called as such: // TwoSum twoSum = new TwoSum(); // twoSum.add(number); // twoSum.find(value);

Shawngbk commented 7 years ago

Linkedin