Tuesday, December 27, 2016

算法小结--HashMap解法

关键代码:
--将HashMap的value导入ArrayList
ArrayList(Collection<? extends E> c)
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
return new ArrayList<List<String>>(map.values());

Set<String> res = new HashSet<String>();
return new ArrayList<String>(res);

--拿来判断是否value一组里有重复
  map.size()==new HashSet<>(map.values()).size();

-- Iteration
for(Integer key:map.keySet()) map.get(key);

-- TreeMap
HashMap的key不是sorted,如果想要sort就用TreeMap(ascending)
TreeMap<Integer,List<Character>> map2 = new TreeMap<Integer,List<Character>>(Collections.reverseOrder()) (descending) 

--Sort TreeMap by val using heap
 HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        PriorityQueue<Character> heap = new PriorityQueue<Character>(new Comparator<Character>(){//need to be 'Integer' or 'Character', map defined that way
            @Override
            public int compare(Character c1, Character c2) {
                return map.get(c2) - map.get(c1);
            }
        });


--Initialize set with values
 HashSet<Character> map = new HashSet<Character>(Arrays.asList('a','e','i','o','u')); EX:

» 205. Isomorphic Strings LinkedIn
https://leetcode.com/problems/isomorphic-strings/ 

» 209. Word Pattern Uber Dropbox
https://leetcode.com/problems/word-pattern/

» 325. Maximum Size Subarray Sum Equals F家
关键是containsKey(sum-k)来看是否有subarray满足条件
http://rainykat.blogspot.com/2016/12/leetcode-facebook-maximum-size-subarray.html


» 1.Two Sum 高频题,各大公司都会考(F家 亚麻 Uber L家...)
http://rainykat.blogspot.com/2016/12/leetcode-two-sum.html 

» 314. BFS -Binary Tree Vertical Order Traversal F家G家 
http://rainykat.blogspot.com/2016/12/leetcodefg-binary-tree-vertical-order.html 

»  409. Longest Palindrome G家
http://rainykat.blogspot.com/2016/12/leetcodeg-longest-palindrome.html

 » 49. Group Anagrams 各大家
sort string[i] alphabetically 来查 key in HashMap
http://rainykat.blogspot.com/2017/01/leetcode-49-group-anagramshashmap.html 

 » 451.Sort Characters By Frequency G家,亚麻
用HashMap 存<char,freq>,然后用max heap 存character by freq using comparator
http://rainykat.blogspot.com.tr/2017/01/leetcodeg-451-sort-characters-by.html

 » 128. Longest Consecutive Sequence(HashMap+UnionFind) F家 G家
难点在于要 updating boundary length to maintain the overall max (eg: [4,5,6,3]3要根据4的结果来计算,得到最长值)
http://rainykat.blogspot.com/2017/01/leetcodefg-128-longest-consecutive.html 

No comments:

Post a Comment