12 2016 档案
Leetcode: LFU Cache && Summary of various Sets: HashSet, TreeSet, LinkedHashSet
摘要:referred to: https://discuss.leetcode.com/topic/69137/java-o-1-accept-solution-using-hashmap-doublelinkedlist-and-linkedhashset Two HashMaps are used,
阅读全文
Leetcode: Poor Pigs
摘要:My binary encoding method gives a 8 for the first problem, however, there is a smarter method that generates a answer of 5, which can be found here: h
阅读全文
Leetcode: Validate IP Address
摘要:Be careful, split() will not include trailing empty strings in the result array The string "boo:and:foo", for example, split(":")的结果是 {“boo”, "and", "
阅读全文
Leetcode: Encode String with Shortest Length && G面经
摘要:DP: Initially I think of 1D DP, dp[i] stands for the shortest string of first i characters, then: dp[i] = minLen{dp[k] + encode(substring(k+1, i))} th
阅读全文
Leetcode: Concatenated Words
摘要:Scan through array and DP: We iterate through each word and see if it can be formed by using other words. The subproblem is Word Break I. But it is a
阅读全文
Leetcode: Convex Polygon
摘要:https://discuss.leetcode.com/topic/70706/beyond-my-knowledge-java-solution-with-in-line-explanation https://discuss.leetcode.com/topic/70664/c-7-line-
阅读全文
Leetcode: Unique Substrings in Wraparound String
摘要:这道题我一开始发现了数学规律: length of consecutive chars vs number of different substring “a” -> 1 = 1 "ab" -> 3 = 1+2 "abc" -> 6 = 1+2+3 "abcd" -> 10 = 1+2+3+4 于是
阅读全文
Leetcode: Matchsticks to Square && Grammar: reverse an primative array
摘要:DFS, my solution is to fill each edge of the square one by one. DFS to construct the 1st, then 2nd, then 3rd, then 4th. For each edge I scan all the m
阅读全文
Leetcode: Serialize and Deserialize BST
摘要:So the first question is: what is the difference between this and #297? This here is BST, however, in #297, it's BT. "The encoded string should be as
阅读全文
Leetcode: Circular Array Loop
摘要:注意The loop must be "forward" or "backward'. 所以这就是为什么[-2, 1, -1, -2, -2]是false的原因 Just think it as finding a loop in Linkedlist, except that loops with
阅读全文
Leetcode: Sequence Reconstruction
摘要:Topological Sort: This problem is to determine if there's one, and only one sequence to sort a DAG. The method is to check if the queue's size is alwa
阅读全文
Leetcode: Ternary Expression Parser
摘要:My First Solution: Use Stack and String operation, from the back of the string, find the first '?', push the right to stack. Depends on whether the ch
阅读全文
Leetcode: Word Squares && Summary: Another Important Implementation of Trie(Retrieve all the words with a given Prefix)
摘要:Backtracking + Trie: referred to https://discuss.leetcode.com/topic/63516/explained-my-java-solution-using-trie-126ms-16-16 A better approach is to ch
阅读全文
Leetcode: Ones and Zeroes
摘要:This is a 0/1 backpacking problem The problem can be interpreted as: What's the max number of str can we pick from strs with limitation of m "0"s and
阅读全文
Leetcode: Heaters
摘要:Binary Search My solution: Be careful in my binary search function, l, r may go out of the range of the array Solution with the highest vote:
阅读全文
Leetcode: Total Hamming Distance
摘要:Example: 0 0 0 0 0 1 0 0 1 1 1 0 0 0 1 0 Total Hamming Distance = (3*1) + (2*2) + (2*2) + (4*0) = 11 so the idea is count the number of 1 and 0 on eac
阅读全文
Leetcode: Valid Word Square
摘要:这题看起来简单但是其实很容易写错 本来想j 不从0开始,而是从 i+1开始检查,可以节省时间,但是一些为Null的情况会使讨论很复杂 比如
阅读全文
Leetcode: Sentence Screen Fitting
摘要:先来一个brute force, 类似Text Adjustment 但是在稍微大一点的case就TLE了,比如: ["a","b","e"] 20000 20000, 花了465ms 所以想想怎么节约时间, 提示是可以DP的,想想怎么复用,refer to: https://discuss.lee
阅读全文
Leetcode: Minimum Unique Word Abbreviation
摘要:Refer to https://discuss.leetcode.com/topic/61799/java-bit-mask-dfs-with-pruning bit mask refer to http://bookshadow.com/weblog/2016/10/02/leetcode-mi
阅读全文
Leetcode: Design Phone Directory
摘要:my HashSet+ ArrayList, 删除的时候把要删的index与末尾对调。get()其实不需要random, 因为anyone is ok HashSet+ Queue网上vote最高的solution,
阅读全文
Leetcode: Valid Word Abbreviation
摘要:Given a non-empty string s and an abbreviation abbr, return whether the string matches with the given abbreviation. A string such as "word" contains only the following valid abbreviations: ["word",...
阅读全文
Leetcode: Find Leaves of Binary Tree
摘要:Better Solution: https://discuss.leetcode.com/topic/49194/10-lines-simple-java-solution-using-recursion-with-explanation/2 For this question we need t
阅读全文
Leetcode: Design Hit Counter
摘要:Use Queue Better Solution: can solve follow up, refer to https://discuss.leetcode.com/topic/48758/super-easy-design-o-1-hit-o-s-gethits-no-fancy-data-
阅读全文
Leetcode: Bomb Enemy
摘要:Walk through the matrix. At the start of each non-wall-streak (row-wise or column-wise), count the number of hits in that streak and remember it. For
阅读全文
Bloomberg面经准备: Josephus problem
摘要:Solution 1: Math Let f(n,k) denote the position of the survivor. After the kth person is killed, we're left with a circle of n-1, and we start the nex
阅读全文
Leetcode: Plus One Linked List
摘要:Solution: Use Stack, O(N) space my another solution: don't create new node, modify the existed node Solution 3: reverse the inputs, add one, then reve
阅读全文
Leetcode: Sort Transformed Array
摘要:参考:https://discuss.leetcode.com/topic/48424/java-o-n-incredibly-short-yet-easy-to-understand-ac-solution the problem seems to have many cases a>0, a=0
阅读全文
Leetcode: Rearrange String k Distance Apart
摘要:Analysis: Solution 1: The greedy algorithm is that in each step, select the char with highest remaining count if possible (if it is not in the waiting
阅读全文
Leetcode: Line Reflection
摘要:本题精妙之处在于:1. 如何最快找到possible的line的x axis(我最开始想到要用quickselect find median的方法,结果别人有min max方法) 2. 如何最方便确定一个点关于该line的reflection是否存在,由于既有x又有y,不太好处理,别人有个聪明的办法
阅读全文
Leetcode: Design Snake Game
摘要:HashSet + Queue: 吃东西的时候保留尾巴,不吃的时候删去尾巴 one case to notice蛇转弯的时候,要先删去尾巴,再把新的点加进去。如果这个顺序不对的话,本来不会撞上尾巴的结果会判断会撞上 如果没有39行,程序会说dir没有initialize, 其实更好的写法应该是
阅读全文
Leetcode: Android Unlock Patterns
摘要:我自己的backtracking做法 最开始把cur设置为一个dummy value 0 最好的DFS with Optimization beat 97%: https://discuss.leetcode.com/topic/46260/java-dfs-solution-with-clear-
阅读全文
Leetcode: Longest Substring with At Most K Distinct Characters && Summary: Window做法两种思路总结
摘要:我的做法:维护一个window,r移动到超出k distinct character限制是更新max,然后移动l使distinct character <=k; 这种做法更新max只发生在超出限制的时候,有可能永远都没有超出限制,所以while loop完了之后要补上一个max的更新 别人非常棒的做
阅读全文
Design Tic-Tac Toe
摘要:Hint: 看了hint之后想到:既然用数组的话,一行一列都是一个element来代表,估计这个element是要用sum了,那么,能不能用sum来代表一行,使它有且只有一种可能,全部是player1完成的/全部是Player2;所以想到了是Player1就+1,是player2就-1,看最后sum
阅读全文
Leetcode: Nested List Weight Sum II
摘要:Inspired by: https://discuss.leetcode.com/topic/49041/no-depth-variable-no-multiplication Instead of multiplying by depth, add integers multiple times
阅读全文
Leetcode: Largest BST Subtree
摘要:refer to https://discuss.leetcode.com/topic/36995/share-my-o-n-java-code-with-brief-explanation-and-comments/2 这道题不好从root到leaf一层一层限制subtree取值范围,因为有可能p
阅读全文
Leetcode: Wiggle Sort II
摘要:这道题应该是hard,首先思想上面参考了https://discuss.leetcode.com/topic/32861/3-lines-python-with-explanation-proof I put the smaller half of the numbers on the even i
阅读全文
Leetcode: Delete Node in a BST
摘要:recursively find the node that needs to be deleted Once the node is found, have to handle the below 4 cases node doesn't have left nor right - return
阅读全文
2Sigma OA prepare: Longest Chain
摘要:DP use HashMap: 根据string的长度sort,然后维护每个string的longest chain,default为1,如果删除某个char生成的string能提供更长的chain,则更新
阅读全文
2Sigma OA prepare: Friends Circle
摘要:DFS & BFS: 关键在于构造graph 如果想把String[] array转化为2d char array, code如下,写的时候这里出了点小问题。friends是String[] Union Find
阅读全文
Leetcode: Find All Numbers Disappeared in an Array
摘要:Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Cou...
阅读全文
Leetcode: Find All Duplicates in an Array
摘要:my solution: put integer A[i] at index A[i]-1 unless A[i] already equals i +1 or A[i] == A[A[i]-1] later scan again if at index i, A[i] != i+1, then A
阅读全文
Leetcode: Minimum Genetic Mutation
摘要:the same with word ladder 写的时候语法上出了一些问题 第5行不用给char数组赋大小 第20行用stringbuilder的时候曾经写成:String afterMutation = new StringBuilder(cur).setCharAt(i, c).toStri
阅读全文
Leetcode: Island Perimeter
摘要:You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely...
阅读全文
Leetcode: Can I Win
摘要:refer to https://discuss.leetcode.com/topic/68896/java-solution-using-hashmap-with-detailed-explanation After solving several "Game Playing" questions
阅读全文
Leetcode: Repeated Substring Pattern
摘要:这道题应该没法用DP等解,只能brute force 或者 KMP(为深究) BruteForce, Best Solution for now except KMP 作为Encode String with Shortest Length的subproblem KMP解法未研究,https://d
阅读全文
Leetcode: Assign Cookies
摘要:Solution 1: Greedy, Time:O(nlogn) Just assign the cookies starting from the child with less greediness to maximize the number of happy children . Solu
阅读全文
Leetcode: 132 Pattern
摘要:我觉得这道题是hard,难点第一是要想到用stack,第二是要维护一个这样子的min-max序列:So at any time in the stack, non-overlapping Pairs are formed in descending order by their min value,
阅读全文
Leetcode: Arithmetic Slices II - Subsequence
摘要:参考了https://discuss.leetcode.com/topic/67413/detailed-explanation-for-java-o-n-2-solution 这道题DP思路还是能想出来,Time O(N^2), Space O(N^2) T(i, d), which denote
阅读全文
Leetcode: Minimum Moves to Equal Array Elements II
摘要:Just like meeting point problem, find the median elements in the array after sorting, so Solution 1: Sort, find the median: O(NlogN) Solution 2: Quick
阅读全文
Leetcode: 4Sum II
摘要:一开始想了一个O(n^3), space O(N)的做法,后来发现还可以优化 Solution: time O(N^2), space O(N^2)
阅读全文
Leetcode: K-th Smallest in Lexicographical Order
摘要:第二遍做法:参考https://discuss.leetcode.com/topic/64624/concise-easy-to-understand-java-5ms-solution-with-explaination Actually this is a denary tree (each n
阅读全文
Leetcode: Minimum Number of Arrows to Burst Balloons
摘要:我的Greedy+Heap做法: Array按start moment升序sort,Heap里按end moment升序sort,一旦到Heap里结束时间最早的气球的end,就要扔arrow,这时在heap里的气球都会被引爆 改进:因为一旦气球爆了的话,Heap里面的元素要全部清空,不需要知道Hea
阅读全文
Leetcode: Minimum Moves to Equal Array Elements
摘要:idea 1: suppose it takes y steps to equal each elements, then this equation stands: (min + y) * num.length == sum + (num.length-1)*y, where min + y is
阅读全文
Leetcode: Number of Boomerangs
摘要:Solution: Use HashTable, Time: O(N^2), Space: O(N) 我的:注意14行是有value个重复distance,表示有value个点,他们跟指定点距离都是distance,需要选取2个做permutation, 所以是value * (value-1) 别
阅读全文
Leetcode: Arranging Coins
摘要:count is the # of level, sum is the accumulated coins Better Solution: Binary Search, 因为怕溢出,所以(1+m)m/2表示成了line6那种样子. 用m去估计最后返回的row
阅读全文
Leetcode: Path Sum III
摘要:Add the prefix sum to the hashMap, and check along path if hashMap.contains(pathSum+cur.val-target); My Solution 一个更简洁的solution: using HashMap to stor
阅读全文
Leetcode: All O`one Data Structure
摘要:Solution: O(1) time complexity 解题思路主要参考了网友ivancjw的帖子,数据结构参考了https://discuss.leetcode.com/topic/65634/java-ac-all-strict-o-1-not-average-o-1-easy-to-re
阅读全文
Leetcode: Find Right Interval
摘要:Solution 1: TreeMap, Time complexity: O(NlogN) 像这种在一个集合里面寻找有没有比某个数小的数,一般要么treeMap要么treeSet。Interval的题经常需要用treeMap, Data Stream as Disjoint Intervals 就
阅读全文
Leetcode: Non-overlapping Intervals
摘要:Actually, the problem is the same as "Given a collection of intervals, find the maximum number of intervals that are non-overlapping." (the classic Gr
阅读全文
Leetcode: Number of Segments in a String
摘要:用split() 不用API, better solution, O(N) time O(1) space
阅读全文
Leetcode: Strong Password Checker
摘要:refer to https://discuss.leetcode.com/topic/63854/o-n-java-solution-by-analyzing-changes-allowed-to-fix-each-problem http://www.cnblogs.com/grandyang/
阅读全文
G 面经 && Leetcode: Longest Repeating Character Replacement
摘要:真是被这道题气死了,总是弄不对 The problem says that we can make at most k changes to the string (any character can be replaced with any other character). So, let's
阅读全文
Leetcode: Reconstruct Original Digits from English
摘要:# of '0': # of 'z' # of '2': # of 'w' 4: u 6: x 8: g 3: h - 8 5: f - 4 7: s - 6 1: o - 0 - 2 - 4 9: i - 5 - 6 - 8 我的code用了一个数组来存char count
阅读全文
Leetcode: Maximum XOR of Two Numbers in an Array
摘要:Solution 1: Bit Manipulation: 这题真心有点难,get the max XOR bit by bit note that if A^B=C, then A^C=B, B^C=A Solution 2: Trie, (未研究) https://discuss.leetcod
阅读全文
Leetcode: Find All Anagrams in a String
摘要:Time Complexity will be O(n) because the "start" and "end" points will only move from left to right once. Sliding Window: Use a count to denote the di
阅读全文
Leetcode: Pacific Atlantic Water Flow
摘要:这题考点在于需要设置两个visited数组 Two Queue and add all the Pacific border to one queue; Atlantic border to another queue. Keep a visited matrix for each queue. I
阅读全文
Leetcode: Partition Equal Subset Sum
摘要:Backpack problem: dp[i][j] means if the first i elements can sum up to value j dp[i][j] = dp[i-1][j] || (j>=nums[i-1] && dp[i-1][j-nums[i-1]]) the res
阅读全文
Leetcode: Arithmetic Slices
摘要:A slice (P, Q)其实就是从P到Q的序列,(P,Q)是arithmetic slice要求是等差数列且至少有三个数,问array里面有多少个这样的(P, Q) 这道题难点在于想到用DP,一旦想到用DP,就迎刃而解 dp[i]表示以i结束的slice有多少个
阅读全文
Leetcode: Trapping Rain Water II
摘要:The above image represents the elevation map [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] before the rain. After the rain, water are trapped between th
阅读全文
Leetcode: Remove K Digits
摘要:Greedy + Stack: 用一个栈维护最后要留存下来的digits 需要注意的是:如果遍历到string的某个char, string后面的char数刚刚好能填满这个栈,那么即使这个char比栈顶还要小,也不出栈,直接入栈 最后要删除leading 0 用char[]实现栈,思路一样,要快很多
阅读全文
Leetcode: Add Strings
摘要:Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is =0 || j>=0 || carry!=0) { 8 int sum = 0; ...
阅读全文
Leetcode: Longest Palindrome
摘要:Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. This is case sensitive, for example "Aa" is not cons...
阅读全文
Leetcode: Queue Reconstruction by Height
摘要:refer to: https://discuss.leetcode.com/topic/60394/easy-concept-with-python-c-java-solution E.g.input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]subar
阅读全文
Leetcode: Frog Jump
摘要:Solution 1: Backtracking, but will TLE Better Solution: DP (refer to https://discuss.leetcode.com/topic/59903/very-easy-to-understand-java-solution-wi
阅读全文
Leetcode: Binary Watch
摘要:Solution 1: Bit Manipulation use Integer.bitCount() Solution 2: Backtracking, 非常精妙之处在于用了两个数组来帮助generate digit(例如:1011 -> 11)
阅读全文
Leetcode: Evaluate Division
摘要:Graph, DFS (1) Build the map, the key is dividend, the value is also a map whose key is divisor and value is its parameter. For example, a / b = 2.0,
阅读全文
Leetcode: Integer Replacement
摘要:Refer to: https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations/2 When to add 1 instead of minus 1, here is an example
阅读全文
Leetcode: Longest Substring with At Least K Repeating Characters
摘要:Analysis: Given a string s, find out all chars that are invalid (i.e., count < k). The longest substring must reside in one of the substrings divided
阅读全文
Leetcode: Rotate Function
摘要:F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 [4, 3, 2, 6] F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 [6,
阅读全文
Leetcode: UTF-8 Validation
摘要:这道题题干给出了判断 one single UTF-8 char的方法,然后给一个UTF-8 char sequence,判断是不是正确sequence. (读题读了很久) 这道题关键是要学到用 & 取出一个bit sequence当中几位的方法 二进制数表示法:在前面加 0b, 八进制加0o, 十
阅读全文
Leetcode: Decode String
摘要:自己的做法:这种括号问题肯定是用栈,最好是先在栈里存一个空元素,然后stack.peek().append()各种操作 一个栈存string, 一个栈存number, 维护一个指针numStart指向数字的开始 1. 遇到数字啥也不做 2. 遇到char: stack.peek().append(c
阅读全文
Leetcode: Perfect Rectangle
摘要:Refer to https://discuss.leetcode.com/topic/56052/really-easy-understanding-solution-o-n-java and https://discuss.leetcode.com/topic/55923/o-n-solutio
阅读全文