12 2015 档案
Leetcode: Coin Change
摘要:You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you nee...
阅读全文
Leetcode: Best Time to Buy and Sell Stock with Cooldown
摘要:Say you have an array for which the ith element is the price of a given stock on day i.Design an algorithm to find the maximum profit. You may complet...
阅读全文
Leetcode: Sparse Matrix Multiplication
摘要:Given two sparse matrices A and B, return the result of AB.You may assume that A's column number is equal to B's row number.Example:A = [ [ 1, 0, 0],...
阅读全文
Leetcode: Expression Add Operators
摘要:参考http://segmentfault.com/a/1190000003797204 and http://blog.csdn.net/u013027996/article/details/48713751 深度优先搜索 复杂度 时间 O(N^2) 空间 O(N) 思路 因为要输出所有可能的情况
阅读全文
Leetcode: Remove Invalid Parentheses
摘要:Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. Note: The input string may cont
阅读全文
Leetcode: Number of Connected Components in an Undirected Graph
摘要:Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected ...
阅读全文
Leetcode: Number of Islands II && Summary of Union Find
摘要:Union Find Princeton's lecture note on Union Find in Algorithms and Data Structures It is a well organized note with clear illustration describing fro
阅读全文
Leetcode: Additive Number
摘要:Additive number is a string whose digits can form additive sequence. A valid additive sequence should contain at least three numbers. Except for the f
阅读全文
Leetcode: Range Sum Query - Immutable
摘要:Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example: Given nums = [-2, 0, 3, -5, 2, -1] sumR
阅读全文
Leetcode: Smallest Rectangle Enclosing Black Pixels
摘要:An image is represented by a binary matrix with 0 as a white pixel and 1 as a black pixel. The black pixels are connected, i.e., there is only one bla
阅读全文
Leetcode: Longest Increasing Subsequence
摘要:讲解一: 用一个数组来存 the smallest tail of all increasing subsequences with length i+1 in tails[i]. For example, say we have nums = [4,5,6,3], then all the ava
阅读全文
Leetcode: Serialize and Deserialize Binary Tree
摘要:Referring this post: https://leetcode.com/problems/serialize-and-deserialize-binary-tree/discuss/74253/Easy-to-understand-Java-Solution But instead us
阅读全文
Leetcode: Binary Tree Longest Consecutive Sequence
摘要:递归法 复杂度 时间O(n) 空间O(h) 思路 因为要找最长的连续路径,我们在遍历树的时候需要两个信息,一是目前连起来的路径(curLen)有多长(以当前节点为终点),二是目前路径的上一个节点的值(preVal)。 每一次递归,先检查当前节点是否比上一节点大1, 是,curLen++, 否curL
阅读全文
Leetcode: Best Meeting Point
摘要:A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the h...
阅读全文
Leetcode: Find Median from Data Stream
摘要:最大最小堆 复杂度 时间 O(logN) insert, O(1) query, 空间 O(N) 思路 维护一个最大堆,一个最小堆。最大堆存的是到目前为止较小的那一半数,最小堆存的是到目前为止较大的那一半数,这样中位数只有可能是堆顶或者堆顶两个数的均值。而维护两个堆的技巧在于判断堆顶数和新来的数的大
阅读全文
Leetcode: Flip Game II
摘要:You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take tu
阅读全文
Leetcode: Flip Game
摘要:You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take tu...
阅读全文
Leetcode: Nim Game
摘要:You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 ston...
阅读全文
Leetcode: Word Pattern II
摘要:Given a pattern and a string str, find if str follows the same pattern.Here follow means a full match, such that there is a bijection between a letter...
阅读全文
Leetcode: Word Pattern
摘要:Given a pattern and a string str, find if str follows the same pattern. Here follow means a full match, such that there is a bijection between a lette
阅读全文
Leetcode: Game of Life
摘要:编解码法 复杂度 时间 O(NN) 空间 O(1) 思路 最简单的方法是再建一个矩阵保存,不过当inplace解时,如果我们直接根据每个点周围的存活数量来修改当前值,由于矩阵是顺序遍历的,这样会影响到下一个点的计算。如何在修改值的同时又保证下一个点的计算不会被影响呢?实际上我们只要将值稍作编码就行了
阅读全文
Leetcode: Alien Dictionary && Summary: Topological Sort
摘要:There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of words from the...
阅读全文
Leetcode: Unique Word Abbreviation
摘要:An abbreviation of a word follows the form . Below are some examples of word abbreviations:a) it --> it (no abbreviation) ...
阅读全文
Leetcode: Find the Duplicate Number
摘要:参考了这个总结,非常详细:http://segmentfault.com/a/1190000003817671 最好方法: 映射找环法 复杂度 时间 O(N) 空间 O(1) 思路 假设数组中没有重复,那我们可以做到这么一点,就是将数组的下标和1到n每一个数一对一的映射起来。比如数组是213,则映射
阅读全文
Leetcode: Walls and Gates
摘要:Push all gates into queue first. Then for each gate update its neighbor cells who is empty and push them to the queue. Repeating above steps until the
阅读全文
Leetcode: Move Zeroes
摘要:第二遍做法: 双指针压缩法:O(N), 空间:O(1) 实际上就是将所有的非0数向前尽可能的压缩,最后把没压缩的那部分全置0就行了。比如103040,先压缩成134,剩余的3为全置为0。过程中需要一个指针记录压缩到的位置。 Q:如果要把所有的0放在前面而不是后面呢?A:同样的解题思路,但是是从后向前
阅读全文
Leetcode: Peeking Iterator
摘要:My thinking is: use a double cache: long cache, when no number is cached, cache = Long.MIN_VALUE. When i call next(), it will firstly check if there's
阅读全文
Leetcode: Inorder Successor in BST
摘要:网上看到更好的方法:https://leetcode.com/discuss/77805/java-5ms-short-code-with-explanations The idea is to compare root's value with p's value if root is not n
阅读全文
Leetcode: Zigzag Iterator
摘要:Best Solution: O(N) This solution also works for K vectors Use a queue to store the iterators in different vectors. Every time we call next(), we pop
阅读全文
Leetcode: Wiggle Sort
摘要:Given an unsorted array nums, reorder it in-place such that nums[0] = nums[2] = nums[i - 1]如果i是偶数,nums[i] nums[i - 1], 则交换以后肯定有nums[i] =nums[i-1])) {...
阅读全文
Leetcode: Perfect Squares
摘要:Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.For example, given n = 12, ...
阅读全文
Leetcode: First Bad Version
摘要:You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality c...
阅读全文
Leetcode: Find the Celebrity
摘要:最佳做法:O(N)time, O(1)space The first pass is to pick out the candidate. If candidate knows i, then switch candidate. The second pass is to check whether
阅读全文
Leetcode: Integer to English Words
摘要:Career Cup 150 Pg 442 Think of Convert(19,323,984) = Process(19) + "million" + Process(323) + "thousand" + Process(984) + "" The Process is a process
阅读全文
Leetcode: Paint Fence
摘要:There is a fence with n posts, each post can be painted with one of the k colors.You have to paint all the posts such that no more than two adjacent f...
阅读全文
Leetcode: H-Index II
摘要:Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm? Hint: Expected runtime complexity
阅读全文
Leetcode: H-Index
摘要:Hint: Sort first then scan: O(NlogN) time, O(1)space use another array: O(N) time, O(N) space(有点像counting sort) 我们额外使用一个大小为N+1的数组stats。stats[i]表示有多少文章
阅读全文
Leetcode: Closest Binary Search Tree Value II
摘要:Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.Note:Given target value is a floating...
阅读全文
Leetcode: Encode and Decode Strings
摘要:If I choose / as spliter, how to ensure the other / wouldn't be seen as spliter? The idea is to store length of the str This one will be encoded as "6
阅读全文
Leetcode: Closest Binary Search Tree Value
摘要:Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.Note:Given target value is a floating...
阅读全文
Leetcode: Missing Number
摘要:Best Solution: Bit manipulation The basic idea is to use XOR operation. We all know that a^b^b =a, which means two xor operations with the same number
阅读全文
Leetcode: Graph Valid Tree && Summary: Detect cycle in undirected graph
摘要:This problem can be solved by using union find, reference this blog:https://segmentfault.com/a/1190000003791051 复杂度 时间 O(N^M) 空间 O(N) 思路 判断输入的边是否能构成一个
阅读全文
Leetcode: Paint House II
摘要:There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. Yo
阅读全文
Leetcode: Palindrome Permutation II
摘要:Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form...
阅读全文
Leetcode: Palindrome Permutation
摘要:Given a string, determine if a permutation of the string could form a palindrome.For example,"code" -> False, "aab" -> True, "carerac" -> True.Hint:Co...
阅读全文
Leetcode: Ugly Number
摘要:Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For exa
阅读全文
Leetcode: Ugly Number II
摘要:Write a program to find the n-th ugly number.Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6...
阅读全文
Leetcode: Single Number III
摘要:Lintcode 也有这道题 Single Number III example: 1 0 1 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 1 如例所示,最后两个数8,
阅读全文
Leetcode: 3Sum Smaller
摘要:Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 =2; i--) { 6 //if (i!=nums.length-1 && (n...
阅读全文
Leetcode: Factor Combinations
摘要:Numbers can be regarded as product of its factors. For example, 8 = 2 x 2 x 2; = 2 x 4. Write a function that takes an integer n and return all possib
阅读全文
Leetcode: Different Ways to Add Parentheses
摘要:用到了Divide and Conquer, 跟 Leetcode: Unique Binary Search Trees II 很像 在input string里遍历各个operator, 依据每个operator分成左右子串,左右子串做递归返回所有可能的results,然后全排列。 注意很巧妙的
阅读全文
Leetcode: Add Digits
摘要:我的方法:注意最方便的获取一个数每一位的方法,是把它转化为String先,通过String.valueOf(int c) O(1): http://my.oschina.net/Tsybius2014/blog/497645 另一个方法比较简单,可以举例说明一下。假设输入的数字是一个5位数字num,
阅读全文
Leetcode: Binary Tree Paths
摘要:Given a binary tree, return all root-to-leaf paths.For example, given the following binary tree: 1 / \2 3 \ 5All root-to-leaf paths are:["1->...
阅读全文
Leetcode: Verify Preorder Sequence in Binary Search Tree
摘要:4 / \ 2 6 / \ / \ 1 3 5 7 如图所示BST, preorder结果是 4 2 1 3 6 5 7 4是root, 213是左子树,657是右子树 idea就是右子树不能再出现比root小的数,一旦出现,return false. 这样一层一层recursion, 直到子树只剩
阅读全文
Leetcode: Meeting Rooms II
摘要:Like the previous one Meeting Room, still need to sort the intervals using a comparator. We need to simulate the process to know the maximum number of
阅读全文
Leetcode: Meeting Rooms
摘要:Interval as an array: Previous interval as an object: Implement a Comparator<Interval> Syntax: don't forget the public sign when defining a function
阅读全文
Leetcode: Flatten 2D Vector
摘要:Implement an iterator to flatten a 2d vector.For example,Given 2d vector =[ [1,2], [3], [4,5,6]]By calling next repeatedly until hasNext returns fa...
阅读全文
Leetcode: Count Univalue Subtrees
摘要:Given a binary tree, count the number of uni-value subtrees.A Uni-value subtree means all nodes of the subtree have the same value.For example:Given b...
阅读全文
Leetcode: Group Shifted Strings
摘要:Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequen...
阅读全文
Leetcode: Strobogrammatic Number III
摘要:A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).Write a function to count the total strobogr...
阅读全文
Leetcode: Strobogrammatic Number II
摘要:Watch out for cornor case: when n = 2, there shouldn't be "00" returned. but when n = 4, which uses n =2 as recursion base, "1001" is an answer
阅读全文
Leetcode: Strobogrammatic Number
摘要:Related to confusing number O(N) time and O(N) space O(N) time and O(1) space, use two pointers
阅读全文
Leetcode: Shortest Word Distance III
摘要:This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.Given a list of words and two words word1 a...
阅读全文
Leetcode: Shortest Word Distance II
摘要:This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and your method will be called repeatedly ma...
阅读全文
Leetcode: Shortest Word Distance
摘要:双指针法:time O(N), space O(1) 一个指针指向word1上次出现的位置,一个指针指向word2上次出现的位置。因为两个单词如果比较接近的话,肯定是相邻的word1和word2的位置之差,所以我们只要每次得到一个新位置和另一个单词的位置比较一下就行了。
阅读全文
Leetcode: Valid Anagram
摘要:还不知道Unicode 该怎么做 只有lowercase alphabets的做法无外乎sort, hashmap, array, bitmap之类的 Better: Unicode Follow up In Java, a Unicode could be represented by a sin
阅读全文
Leetcode: Search a 2D Matrix II
摘要:Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted i
阅读全文
Leetcode: Sliding Window Maximum
摘要:方法一:Heap时间 O(NlogK) 空间 O(K) maintain a maximum heap, notice PriorityQueue.remove(object o) can remove certain object from our heap. When writting Maxi
阅读全文
Leetcode: Product of Array Except Self
摘要:Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except ...
阅读全文
Leetcode: Delete Node in a Linked List
摘要:Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Supposed the linked list is 1 -> 2 -> 3 -
阅读全文
Leetcode: Lowest Common Ancestor of a Binary Tree
摘要:Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.According to the definition of LCA on Wikipedia: “The lowest...
阅读全文
Leetcode: Lowest Common Ancestor of a Binary Search Tree
摘要:Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia
阅读全文
Leetcode: Palindrome Linked List
摘要:Given a singly linked list, determine if it is a palindrome.Follow up:Could you do it in O(n) time and O(1) space?先分成大小相同(可能长度差1) 两部分, reverse一个list. ...
阅读全文
Leetcode: Number of Digit One
摘要:Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.For example:Given n = 13,Return 6...
阅读全文
Leetcode: Power of Two
摘要:Best Solution 还是有一个地方不小心:Integer.MIN_VALUE, 应该是false,但是因为只有一个1,我曾经判断为true。事实上,所有negative value都应该是false 一旦符号位为1,就return false, 检查其他位只有1个1 做的时候遇到很多语法错误
阅读全文
Leetcode: Implement Queue using Stacks
摘要:Implement the following operations of a queue using stacks.push(x) -- Push element x to the back of queue.pop() -- Removes the element from in front o...
阅读全文
Leetcode: Majority Element II
摘要:Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.Hin...
阅读全文
Leetcode: Kth Smallest Element in a BST
摘要:Java Solution 1 - Inorder Traversal We can inorder traverse the tree and get the kth smallest element. Time is O(n). Recursion method: Java Solution 2
阅读全文
Leetcode: Basic Calculator II
摘要:用Stack来做:时间 O(N) 空间 O(N) 因为乘法和除法不仅要知道下一个数,也要知道上一个数。所以我们用一个栈把上次的数存起来,遇到加减法就直接将数字压入栈中,遇到乘除法就把栈顶拿出来乘或除一下新数,再压回去。最后我们把栈里所有数加起来就行了。 上面这段code可以先用String.repl
阅读全文
Leetcode: Basic Calculator
摘要:https://discuss.leetcode.com/topic/15816/iterative-java-solution-with-stack 第二遍做法:遇到digit直接走到末尾,并且直接利用sign进行计算,这样比较方便 第一遍做法:
阅读全文
Leetcode: Count Complete Tree Nodes
摘要:递归树高法 复杂度 时间 O(N) 空间 O(1) 思路 完全二叉树的一个性质是,如果左子树最左边的深度,等于右子树最右边的深度,说明这个二叉树是满的,即最后一层也是满的,则以该节点为根的树其节点一共有2^h-1个。如果不等于,则是左子树的节点数,加上右子树的节点数,加上自身这一个。 注意 这里在左
阅读全文
Leetcode: Implement Stack using Queues
摘要:Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. to
阅读全文
Leetcode: Maximal Square
摘要:dp问题,用一个dp[i][j]保存matrix[i][j]作为右下节点的时候的最大矩形的边长 if (matrix[i][j] == '0') dp[i][j] = 0; else dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1;
阅读全文
Leetcode: Contains Duplicate III
摘要:暴力枚举会LTE,解题思路是用sortedSet来解决,sortedSet可以返回一个在某个范围的subSet,同时判断这个subSet是否为空即可解决,主要,本题需要使用long类型! 时间 O(NlogK) 空间 O(K) 思路 要求判断之前是否存在差值小于t的数字,我们需要知道在当前数字x两边
阅读全文
Leetcode: Invert Binary Tree
摘要:nvert a binary tree. 4 / \ 2 7 / \ / \1 3 6 9to 4 / \ 7 2 / \ / \9 6 3 1Trivia:This problem was inspired by this...
阅读全文
Leetcode: The Skyline Problem
摘要:参考了http://www.cnblogs.com/tonyluis/p/4564617.html 复杂度 Time Complexity is O(n^2) because removal in a PQ is O(n), 空间 O(N) I think if replace PQ with Tr
阅读全文
Leetcode: Word Search II
摘要:如果跟Word Search做法一样,还按照DFS回溯的方法,逐个检查每个word是否在board里,显然效率是比较低的。我们可以利用Trie数据结构,也就是前缀树。然后dfs时,如果当前形成的单词不在Trie里,就没必要继续dfs下去了。如果当前字符串在trie里,就说明board可以形成这个wo
阅读全文
Leetcode: Rectangle Area
摘要:Find the total area covered by two rectilinear rectangles in a 2D plane.Each rectangle is defined by its bottom left corner and top right corner as sh...
阅读全文
Leetcode: Shortest Palindrome
摘要:本题最简单的思路是从后往前判断子串是否是回文串,然后把后面的弄到前面即可,不过这样仅仅能擦边通过测试 Brute Force: O(N^2), space O(1) DP: O(N^2), space O(N^2) KMP介绍:http://kb.cnblogs.com/page/176818/ 实
阅读全文
Leetcode: Combination Sum III
摘要:ind all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a...
阅读全文
Leetcode: House Robber II
摘要:Analysis: if the last one is not robbed, then you are free to choose whether to rob the first one. you can break the circle by assuming the first hous
阅读全文
Leetcode: Contains Duplicate II
摘要:Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the ...
阅读全文
Leetcode: Kth Largest Element in an Array
摘要:Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.For examp...
阅读全文
Leetcode: Minimum Size Subarray Sum
摘要:Haven't think about the O(nlogn) solution. O(n) solution is to maintain a window My solution: shrink as much as possible while maintaining the window
阅读全文
Leetcode: Add and Search Word - Data structure design
摘要:方法1:brute force: search function compares each word with the pattern, time complexity: O(nk), n is number of words in dictionary, k is averge length 方
阅读全文
Leetcode: Implement Trie (Prefix Tree) && Summary: Trie
摘要:参考百度百科:Trie树 a trie, also called digital tree and sometimes radix tree or prefix tree (as they can be searched by prefixes) The time complexity to ins
阅读全文
Leetcode: Course Schedule II
摘要:There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prerequisites, for example to take course 0 you have t
阅读全文
Leetcode: Course Schedule
摘要:The hint provided by leetcode is: Hints: BFS: 典型的拓扑排序。原理也很简单,在一个有向图中,每次找到一个没有前驱节点的节点(也就是入度为0的节点),然后把它指向其他节点的边都去掉,重复这个过程(BFS),直到所有节点已被找到,或者没有符合条件的节点(如果
阅读全文
Leetcode: Isomorphic Strings
摘要:Best: O(N) time, constant space 复杂度 时间 O(N) 空间 O(N) 思路 用一个哈希表记录字符串s中字母到字符串t中字母的映射关系,一个集合记录已经映射过的字母。或者用两个哈希表记录双向的映射关系。这里不能只用一个哈希表,因为要排除egg->ddd这种多对一的映射
阅读全文
Leetcode: Reverse Linked List
摘要:基本迭代 Time: O(N), Space: O(1) 基本递归 Time: O(N), Space: O(N)递归栈大小
阅读全文
Leetcode: Count Primes
摘要:Count the number of prime numbers less than a non-negative number, n.Algorithm: The sieve of Eratosthenes,Referring to Summary: Primes0 and 1 are not ...
阅读全文
Leetcode: Remove Linked List Elements
摘要:set Dummy node 这题有个重要的follow up,就是在一个环里怎么删除节点: 参考:http://www.cnblogs.com/EdwardLiu/p/5975748.html
阅读全文
Leetcode: Bitwise AND of Numbers Range
摘要:Given a range [m, n] where 0 maxRange) continue; 9 int mi = (m>>i) & 1;10 int ni = (n>>i) & 1;11 if (mi == 1 && n...
阅读全文
Leetcode: Happy Number
摘要:Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive intege
阅读全文