Thursday, August 11, 2016
LeetCode [359] Logger Rate Limiter
Design a logger system that receive stream of messages along with its timestamps, each message should be printed if and only if it is not printed in the last 10 seconds.
Given a message and a timestamp (in seconds granularity), return true if the message should be printed in the given timestamp, otherwise returns false.
It is possible that several messages arrive roughly at the same time.
Example:
Logger logger = new Logger(); // logging string "foo" at timestamp 1 logger.shouldPrintMessage(1, "foo"); returns true; // logging string "bar" at timestamp 2 logger.shouldPrintMessage(2,"bar"); returns true; // logging string "foo" at timestamp 3 logger.shouldPrintMessage(3,"foo"); returns false; // logging string "bar" at timestamp 8 logger.shouldPrintMessage(8,"bar"); returns false; // logging string "foo" at timestamp 10 logger.shouldPrintMessage(10,"foo"); returns false; // logging string "foo" at timestamp 11
logger.shouldPrintMessage(11,"foo"); returns true;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class Logger { Map<String, Integer> map; /** Initialize your data structure here. */ public Logger() { map = new HashMap<>(); } /** Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timestamp is in seconds granularity. */ public boolean shouldPrintMessage(int timestamp, String message) { if(map.isEmpty() || !map.containsKey(message) || timestamp-map.get(message)+1>10){ map.put(message, timestamp); return true; }else{ return false; } } } /** * Your Logger object will be instantiated and called as such: * Logger obj = new Logger(); * boolean param_1 = obj.shouldPrintMessage(timestamp,message); */ |
LeetCode [358] Rearrange String k Distance Apart
""
.Input: s = "aabbcc", k = 3 Output: "abcabc" Explanation: The same letters are at least distance 3 from each other.
Input: s = "aaabc", k = 3 Output: "" Explanation: It is not possible to rearrange the string.
Input: s = "aaadbbcc", k = 2 Output: "abacabcd" Explanation: The same letters are at least distance 2 from each other.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class Solution { public: //find the next valid char can be pus at "index" int getChar(vector<int>& counts, vector<int>& valid, int index) { int m = 0, offset = -1; for(int i=0; i<26; ++i) { if(counts[i]>m && index>=valid[i]) { m = counts[i];//greedy: use the char with max count offset = i; } } return offset; } string rearrangeString(string s, int k) { if(k==0) return s; int n = s.size(); vector<int> counts(26, 0);//counts[i] is count of char('a'+i) vector<int> valid(26, 0);//valid[i] is the next smallest valid position of char('a'+i) for(auto c:s) counts[c-'a']++; string ret; for(int i=0; i<n; ++i) { int offset = getChar(counts, valid, i); if(offset<0) return "";//cannot find a valid char ret += ('a'+offset); counts[offset]--; valid[offset] = i+k; } return ret; } }; |
LeetCode [353] Design Snake Game
Given width = 3, height = 2, and food = [[1,2],[0,1]]. Snake snake = new Snake(width, height, food); Initially the snake appears at position (0,0) and the food at (1,2). |S| | | | | |F| snake.move("R"); -> Returns 0 | |S| | | | |F| snake.move("D"); -> Returns 0 | | | | | |S|F| snake.move("R"); -> Returns 1 (Snake eats the first food and right after that, the second food appears at (0,1) ) | |F| | | |S|S| snake.move("U"); -> Returns 1 | |F|S| | | |S| snake.move("L"); -> Returns 2 (Snake eats the second food) | |S|S| | | |S| snake.move("U"); -> Returns -1 (Game over because snake collides with border)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | class SnakeGame { set<pair<int, int>> hist; //keep the coordinates of the current snake. used to decide if the snake eats itself deque<pair<int, int>> snake; //also keep the snake coordinates. used to update the snake body after each movement vector<vector<int>> food; int pos; //store the food position int w, h; public: /** Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */ SnakeGame(int width, int height, vector<vector<int>> &food) { w = width; h = height; pos = 0; this->food = food; pair<int, int> p = make_pair(0, 0); snake.push_front(p); hist.insert(p); } /** Moves the snake. @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down @return The game's score after the move. Return -1 if game over. Game over when snake crosses the screen boundary or bites its body. */ int move(string direction) { pair<int, int> tail = snake.back(); pair<int, int> head = snake.front(); //remove the tail snake.pop_back(); hist.erase(tail); if (direction == "U") head.first--; if (direction == "L") head.second--; if (direction == "R") head.second++; if (direction == "D") head.first++; //game over if (head.first < 0 || head.first >= h || head.second < 0 || head.second >= w || hist.count(head)) return -1; //add new head snake.push_front(head); hist.insert(head); //no more food. score is the snake size minus the original size 1 if (pos == food.size()) return snake.size() - 1; //extend the snake body by adding the tail back if (head.first == food[pos][0] && head.second == food[pos][1]) { snake.push_back(tail); hist.insert(tail); pos++; } return snake.size() - 1; } }; /** * Your SnakeGame object will be instantiated and called as such: * SnakeGame* obj = new SnakeGame(width, height, food); * int param_1 = obj->move(direction); */ |
class SnakeGame { int foodIndex = 0; Set<Integer> hist = new HashSet<>(); Deque<Integer> body = new LinkedList<>(); int w, h; int[][] food; /** Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */ public SnakeGame(int width, int height, int[][] food) { w = width; h = height; this.food = food; body.add(0); } /** Moves the snake. @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down @return The game's score after the move. Return -1 if game over. Game over when snake crosses the screen boundary or bites its body. */ public int move(String direction) { int head = body.peekFirst(); int tail = body.peekLast(); //remove tail body.removeLast(); hist.remove(tail); int i = head/w, j = head%w; if(direction.equals("U")) i--; if(direction.equals("D")) i++; if(direction.equals("L")) j--; if(direction.equals("R")) j++; int newPostion = i*w+j; //game over if(i<0 || i>=h || j<0 || j>=w || hist.contains(newPostion)) return -1; //add new head body.addFirst(newPostion); hist.add(newPostion); //no more food, score is body size -1 if(foodIndex == food.length) return body.size()-1; //eat food, body length increases by 1 to the end if(i==food[foodIndex][0] && j==food[foodIndex][1]){ body.add(tail); hist.add(tail); foodIndex++; } return body.size()-1; } } /** * Your SnakeGame object will be instantiated and called as such: * SnakeGame obj = new SnakeGame(width, height, food); * int param_1 = obj.move(direction); */
LeetCode [351] Android Unlock Patterns
351. Android Unlock Patterns
Given an Android 3x3 key lock screen and two integers m and n, where 1 ≤ m ≤ n ≤ 9, count the total number of unlock patterns of the Android lock screen, which consist of minimum of m keys and maximum n keys.
Rules for a valid pattern:
- Each pattern must connect at least m keys and at most n keys.
- All the keys must be distinct.
- If the line connecting two consecutive keys in the pattern passes through any other keys, the other keys must have previously selected in the pattern. No jumps through non selected key is allowed.
- The order of keys used matters.
Explanation:
| 1 | 2 | 3 | | 4 | 5 | 6 | | 7 | 8 | 9 |
Invalid move: 4 - 1 - 3 - 6
Line 1 - 3 passes through key 2 which had not been selected in the pattern.
Invalid move: 4 - 1 - 9 - 2
Line 1 - 9 passes through key 5 which had not been selected in the pattern.
Valid move: 2 - 4 - 1 - 3 - 6
Line 1 - 3 is valid because it passes through key 2, which had been selected in the pattern
Valid move: 6 - 5 - 4 - 1 - 9 - 2
Line 1 - 9 is valid because it passes through key 5, which had been selected in the pattern.
Example:
Input: m = 1, n = 1 Output: 9
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | public class Solution { // cur: the current position // remain: the steps remaining int DFS(boolean vis[], int[][] skip, int cur, int remain) { if(remain < 0) return 0; if(remain == 0) return 1; vis[cur] = true; int rst = 0; for(int i = 1; i <= 9; ++i) { // If vis[i] is not visited and (two numbers are adjacent or skip number is already visited) if(!vis[i] && (skip[cur][i] == 0 || (vis[skip[cur][i]]))) { rst += DFS(vis, skip, i, remain - 1); } } vis[cur] = false; return rst; } public int numberOfPatterns(int m, int n) { // Skip array represents number to skip between two pairs int skip[][] = new int[10][10]; skip[1][3] = skip[3][1] = 2; skip[1][7] = skip[7][1] = 4; skip[3][9] = skip[9][3] = 6; skip[7][9] = skip[9][7] = 8; skip[1][9] = skip[9][1] = skip[2][8] = skip[8][2] = skip[3][7] = skip[7][3] = skip[4][6] = skip[6][4] = 5; boolean vis[] = new boolean[10]; int rst = 0; // DFS search each length from m to n for(int i = m; i <= n; ++i) { rst += DFS(vis, skip, 1, i - 1) * 4; // 1, 3, 7, 9 are symmetric rst += DFS(vis, skip, 2, i - 1) * 4; // 2, 4, 6, 8 are symmetric rst += DFS(vis, skip, 5, i - 1); // 5 } return rst; } } |
Monday, July 25, 2016
LeetCode [350] Intersection of Two Arrays II
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9]
Note:
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
Follow up:
- What if the given array is already sorted? How would you optimize your algorithm?
- What if nums1's size is small compared to nums2's size? Which algorithm is better?
- What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { unordered_map<int, int> mp;//number, count for(auto n:nums1) mp[n]++; vector<int> ret; for(auto n:nums2){ if(mp.count(n) && mp[n]>0){ mp[n]--; ret.push_back(n); } } return ret; } }; |
LeetCode [349] Intersection of Two Arrays
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4]
- Each element in the result must be unique.
- The result can be in any order.
1 2 3 4 5 6 7 8 9 10 11 12 | class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { set<int> st(nums1.begin(), nums1.end()); set<int> st1; for(auto n:nums2){ if(st.count(n)) st1.insert(n); } vector<int> ret(st1.begin(), st1.end()); return ret; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); vector<int> ret; int i=0, j = 0, n1 = nums1.size(), n2 = nums2.size(); while(i<n1 && j<n2){ if(nums1[i]<nums2[j]) i++; else if(nums1[i]>nums2[j]) j++; else{ if(ret.empty() || ret.back()!=nums1[i]){ ret.push_back(nums1[i]); } i++; j++; } } return ret; } }; |
LeetCode [348] Design Tic-Tac-Toe
- A move is guaranteed to be valid and is placed on an empty block.
- Once a winning condition is reached, no more moves is allowed.
- A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game.
Given n = 3, assume that player 1 is "X" and player 2 is "O" in the board. TicTacToe toe = new TicTacToe(3); toe.move(0, 0, 1); -> Returns 0 (no one wins) |X| | | | | | | // Player 1 makes a move at (0, 0). | | | | toe.move(0, 2, 2); -> Returns 0 (no one wins) |X| |O| | | | | // Player 2 makes a move at (0, 2). | | | | toe.move(2, 2, 1); -> Returns 0 (no one wins) |X| |O| | | | | // Player 1 makes a move at (2, 2). | | |X| toe.move(1, 1, 2); -> Returns 0 (no one wins) |X| |O| | |O| | // Player 2 makes a move at (1, 1). | | |X| toe.move(2, 0, 1); -> Returns 0 (no one wins) |X| |O| | |O| | // Player 1 makes a move at (2, 0). |X| |X| toe.move(1, 0, 2); -> Returns 0 (no one wins) |X| |O| |O|O| | // Player 2 makes a move at (1, 0). |X| |X| toe.move(2, 1, 1); -> Returns 1 (player 1 wins) |X| |O| |O|O| | // Player 1 makes a move at (2, 1). |X|X|X|
Could you do better than O(n2) per
move()
operation?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | class TicTacToe { public: vector<int> cols, rows; int diagonal, antiDiagonal; /** Initialize your data structure here. */ TicTacToe(int n) : diagonal(0), antiDiagonal(0) { cols = vector<int>(n); rows = vector<int>(n); } /** Player {player} makes a move at ({row}, {col}). @param row The row of the board. @param col The column of the board. @param player The player, can be either 1 or 2. @return The current winning condition, can be either: 0: No one wins. 1: Player 1 wins. 2: Player 2 wins. */ int move(int row, int col, int player) { int toAdd = player == 1 ? 1 : -1; rows[row] += toAdd; cols[col] += toAdd; if (row == col) { diagonal += toAdd; } int len = rows.size(); if (row == len-col-1) { antiDiagonal += toAdd; } if (abs(rows[row]) == len || abs(cols[col]) == len || abs(diagonal) == len || abs(antiDiagonal) == len) { return player; } return 0; } }; |