美文网首页
170. Two Sum III - Data structur

170. Two Sum III - Data structur

作者: Super_Alan | 来源:发表于2018-04-20 00:47 被阅读0次

    https://leetcode.com/problems/two-sum-iii-data-structure-design/description/

    Time Limit Exceeded:

    class TwoSum {
        private LinkedList<Integer> list;
        private HashSet<Integer> set;
            
        /** Initialize your data structure here. */
        public TwoSum() {
            list = new LinkedList<>();
            set = new HashSet<>();
        }
        
        /** Add the number to an internal data structure.. */
        public void add(int number) {
            for (int item: list) {
                set.add(item + number);
            }
            list.add(number);
        }
        
        /** Find if there exists any pair of numbers which sum is equal to the value. */
        public boolean find(int value) {
            return set.contains(value);
        }
    }
    

    passed: LinkedList + HashMap

    这种解法有两个好处:

    • 易于重复性很多的数值
    • Extension: 如果需要进行删除操作, 这种写法更容易。

    个人更喜欢上面 HashSet 的解法,find 操作 O(1)。看哪个操作使用的更频繁了。

    class TwoSum {
        private LinkedList<Integer> list;   // uniq number
        private HashMap<Integer, Integer> map; // item and its count
            
        /** Initialize your data structure here. */
        public TwoSum() {
            list = new LinkedList<>();
            map = new HashMap<>();
        }
        
        /** Add the number to an internal data structure.. */
        public void add(int num) {
            if (map.containsKey(num)) {
                map.put(num, map.get(num) + 1);
            } else {
                map.put(num, 1);
                list.add(num);
            }        
        }
        
        /** Find if there exists any pair of numbers which sum is equal to the value. */
        public boolean find(int value) {
            for (Integer num1: list) {
                int num2 = value - num1;
                if ((num1 == num2 && map.get(num1) >= 2) || (num1 != num2) && map.containsKey(num2)) {
                    return true;
                } 
            }
            return false;
        }
    }
    

    相关文章

      网友评论

          本文标题:170. Two Sum III - Data structur

          本文链接:https://www.haomeiwen.com/subject/pdlnkftx.html