<Trie> 212 <Array> 229
212. Word Search II
class TrieNode{ char val; TrieNode[] children; String word; public TrieNode(char x){ children = new TrieNode[26]; word = null; } } class Solution { public List<String> findWords(char[][] board, String[] words) { List<String> res = new ArrayList<>(); if(board == null || board.length == 0) return res; TrieNode root = new TrieNode(' '); buildTrie(root, words); for(int i = 0; i < board.length; i++){ for(int j = 0; j < board[0].length; j++){ char c = board[i][j]; if(root.children[c - 'a'] != null){ dfs(board, i, j, root, res); } } } return res; } private void buildTrie(TrieNode root, String[] words){ for(String s : words){ TrieNode cur = root; for(char c : s.toCharArray()){ if(cur.children[c - 'a'] == null){ cur.children[c - 'a'] = new TrieNode(c); } cur = cur.children[c - 'a']; } cur.word = s; } } private void dfs(char[][] board, int i, int j, TrieNode cur, List<String> res){ if(i < 0 || i >= board.length || j < 0 || j >= board[0].length) return; char c = board[i][j]; if(c == '*') return; if(cur.children[c - 'a'] == null) return; cur = cur.children[c - 'a']; if(cur.word != null){ res.add(cur.word); cur.word = null; } board[i][j] = '*'; dfs(board, i + 1, j, cur, res); dfs(board, i - 1, j, cur, res); dfs(board, i, j + 1, cur, res); dfs(board, i, j - 1, cur, res); board[i][j] = c; } }
229. Majority Element II
Boyer-Moore Majority Vote algorithm
这道题让我们求出现次数大于 n/3 的数字,而且限定了时间和空间复杂度,那么就不能排序,也不能使用 HashMap,这么苛刻的限制条件只有一种方法能解了,那就是摩尔投票法 Moore Voting,这种方法在之前那道题Majority Element中也使用了。
- given n numbers and 1 counter (which is the majority element problem), at most (n/2) times pair-out can happen, which will lead to the survival of the only element that appeared more than n/2 times.
- given n numbers and 2 counters (which is our case), at most n/3 times of pair-out can happen, which will lead to the survival of elements that appeared more than n/3 times.
- given n numbers and k counters, at most (n/k+1) times of pair-out can happen, which will lead to the survival of elements that appeared more than n/(k+1) times.
当出现次数超过n/2的数的时候,只需要1个counter, 出现次数超过n/3的时候,需要2个counter,以此类推。
public class Solution { public List<Integer> majorityElement(int[] nums) { List<Integer> res = new ArrayList<>(); if(nums.length == 0) return res; int num1 = nums[0]; int num2 = nums[0]; int count1 = 0; int count2 = 0 ; for (int val : nums) { if(val == num1) count1++; else if (val == num2) count2++; else if (count1 == 0) { num1 = val; count1++; } else if (count2 == 0) { num2 = val; count2++; } else { count1--; count2--; } } count1 = 0; count2 = 0; for(int val : nums) { if(val == num1) count1++; else if(val == num2) count2++; } if(count1 > nums.length/3) res.add(num1); if(count2 > nums.length/3) res.add(num2); return res; } }