06 2015 档案
摘要:Each time we find a match, increase the global counter by 1.For KMP, algorithm, you may refer to the following links which have nice explanations.KMP ...
阅读全文
摘要:Well, this problem becomes a little trickier since there may be more than one majority element. But, there can be at most two of them. This can be pro...
阅读全文
摘要:Well, if you have got this problem accepted, you may have noticed that there are 7 suggested solutions for this problem. The following passage will im...
阅读全文
摘要:1 class Solution { 2 public: 3 /** 4 * @param dictionary: a vector of strings 5 * @return: a vector of strings 6 */ 7 vector l...
阅读全文
摘要:1 class Solution { 2 public: 3 /** 4 * @param string: An array of Char 5 * @param length: The true length of the string 6 * @retur...
阅读全文
摘要:暴力解法(O(mn)): 1 class Solution { 2 public: 3 /** 4 * Returns a index to the first occurrence of target in source, 5 * or -1 if target is...
阅读全文
摘要:1 /** 2 * Definition of ListNode 3 * class ListNode { 4 * public: 5 * int val; 6 * ListNode *next; 7 * ListNode(int val) { 8 * ...
阅读全文
摘要:Well, life gets difficult pretty soon whenever the same operation on array is transferred to linked list.First, a quick recap of insertion sort:Start ...
阅读全文
摘要:1 class Solution { 2 public: 3 /** 4 * @param A: sorted integer array A which has m elements, 5 * but size of A is m+n 6 ...
阅读全文
摘要:The recursive solution is trivial and I omit it here.Iterative Solution using Stack (O(n)time andO(n)space): 1 /** 2 * Definition of TreeNode: 3 * c...
阅读全文
摘要:A subroutine of merge sort. 1 class Solution { 2 public: 3 /** 4 * @param A and B: sorted integer array A and B. 5 * @return: A new sort...
阅读全文
摘要:The recursive solution is trivial and I omit it here.Iterative Solution using Stack (O(n)time andO(n)space): 1 /** 2 * Definition of TreeNode: 3 * c...
阅读全文
摘要:The recursive solution is trivial and I omit it here.Iterative Solution using Stack (O(n) time and O(n) space): 1 /** 2 * Definition of TreeNode: 3 ...
阅读全文
摘要:动态规划:lis[i] = max_{j = 0, 1, ..., i - 1, nums[j] nums) { 8 // write your code here 9 vector lis(nums.size(), 1);10 int maxlen...
阅读全文
摘要:1 class Solution { 2 public: 3 /** 4 * @param strs: A list of strings 5 * @return: The longest common prefix 6 */ 7 string...
阅读全文
摘要:Bit-by-Bit summation: 1 class Solution { 2 public: 3 /* 4 * @param a: The first integer 5 * @param b: The second integer 6 * @retur...
阅读全文
摘要:The hints of the problem has given detailed information to implement the topological sorting algorithm. In fact, the toposort algorithm of the hint is...
阅读全文
摘要:BFS: 1 /** 2 * Definition for Directed graph. 3 * struct DirectedGraphNode { 4 * int label; 5 * vector neighbors; 6 * DirectedGraphNo...
阅读全文
摘要:基于快速排序: 1 class Solution { 2 public: 3 /* 4 * param k : description of k 5 * param nums : description of array and index 0 ~ n-1 6 ...
阅读全文
摘要:1 class Solution { 2 public: 3 /** 4 * @param grid: a list of lists of integers. 5 * @return: An integer, minimizes the sum of all numb...
阅读全文
摘要:Well, to compute the number of trailing zeros, we need to first think clear about what will generate a trailing0? Obviously, a number multiplied by10w...
阅读全文
摘要:1 class Solution { 2 public: 3 // param n : description of n 4 // return: description of return 5 long long trailingZeros(long long n) ...
阅读全文
摘要:Well, the basic idea is very simple. Start from the tail ofsand move backwards to find the first non-space character. Then from this character, move b...
阅读全文
摘要:1 class Solution { 2 public: 3 /** 4 * @param s A string 5 * @return the length of last word 6 */ 7 int lengthOfLastWord(strin...
阅读全文
摘要:1 class Solution { 2 public: 3 /** 4 * @param s A string 5 * @return Whether the string is a valid palindrome 6 */ 7 bool isPa...
阅读全文
摘要:1 class Solution { 2 public: 3 /** 4 * @param s A string 5 * @return whether the string is a valid parentheses 6 */ 7 bool isV...
阅读全文
摘要:递归实现: 1 /** 2 * Definition of TreeNode: 3 * class TreeNode { 4 * public: 5 * int val; 6 * TreeNode *left, *right; 7 * TreeNode(int v...
阅读全文
摘要:1 class MinStack { 2 public: 3 MinStack() { 4 // do initialization if necessary 5 } 6 7 void push(int number) { 8 // wri...
阅读全文
摘要:1 class Queue { 2 public: 3 stack stack1; 4 stack stack2; 5 6 Queue() { 7 // do intialization if necessary 8 } 9 10 void...
阅读全文
摘要:1 class Solution { 2 public: 3 /** 4 * @param A, B: Two strings. 5 * @return: The length of longest common subsequence of A and B. 6 ...
阅读全文
摘要:1 class Solution { 2 public: 3 /** 4 * @param A, B: Two string. 5 * @return: the length of the longest common substring. 6 */ ...
阅读全文
摘要:Well, this problem is spiritually similar to toCourse Schedule. You only need to store the nodes in the order you visit into a vector during BFS or DF...
阅读全文
摘要:As suggested by the hints, this problem is equivalent to detecting a cycle in the graph represented byprerequisites. Both BFS and DFS can be used to s...
阅读全文
摘要:Topological sort is an important application of DFS in directed acyclic graphs (DAG). For each edge (u, v) from node u to node v in the graph, u must ...
阅读全文
摘要:Graph is an important data structure and has many important applications. Moreover, grach traversal is key to many graph algorithms.There are two syst...
阅读全文
摘要:Problem Description:Given two strings S and T, determine if they are both one edit distance apart.To solve this problem, you first need to know what i...
阅读全文
摘要:This problem is similar to Missing Ranges and easier than that one.The idea is to use two pointers to find the beginning and end of a range and then p...
阅读全文
摘要:Problem Description:Given a sorted integer array where the range of elements are [lower,upper] inclusive, return its missing ranges.For example, given...
阅读全文
摘要:Well, the key to this problem is on how to identify the recurring parts. After doing some examples using pen and paper, you may find that for the deci...
阅读全文
摘要:The problem statement has stated that there are bothO(n)andO(nlogn)solutions to this problem. Let's see theO(n)solution first (taken fromthis link), w...
阅读全文
摘要:Problem Description:Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.The input string d...
阅读全文
摘要:This link has a great discussion about this problem. You may refer to it if you like. In fact, the idea and code in this passage is from the former li...
阅读全文
摘要:Well, this problem has a nice BFS structure.Let's see the example in the problem statement.start = "hit"end = "cog"dict = ["hot", "dot", "dog", "lot",...
阅读全文
摘要:This problem is not quite difficult (a typical BFS traversal of graph), though, its aceptance rate is relatively low. In fact, the key obstacle in pas...
阅读全文
摘要:This problem is an application of graph traversal, which has two systematic methods:Bread-First Search (BFS)andDepth-First Search (DFS). In the follow...
阅读全文
摘要:To solve this problem, some observations have to be made first.Let's first see two relatively easy observations.To maximize the probability that we ca...
阅读全文
摘要:This is a typical problem aboutsearching. In fact, you can use either BFS or DFS for it. Personally, I use BFS because I think it is more intuitive an...
阅读全文
摘要:The basic idea of is as follows:Maintain a dequeoperandsfor the numbers and another dequeoperationsfor the operators+, -, *,/`.Scan the expression fro...
阅读全文
摘要:This problem can be solved elegantly using dynamic programming.We maintain two arrays:cnt[i][j] --- number of parentheses needed to add within s[i..j]...
阅读全文
摘要:KMP is a classic and yet notoriously hard-to-understand algorithm. However, I think the following two links give nice explanations. You may refer to t...
阅读全文
摘要:Well, a typical backtracking problem. Make sure you are clear with the following three problems:What is a partial solution and when is it finished? --...
阅读全文
摘要:Well, a typical backtracking problem. Make sure you are clear with the following three problems:What is a partial solution and when is it finished? --...
阅读全文
摘要:A typical backtracking problem. For any backtracking problem, you need to be think about three ascepts:What is a partial solution and when is it finis...
阅读全文
摘要:The Longest Increasing Subsequence (LIS) problem requires us to find a subsequence t of a given sequence s, such that t satisfies two requirements:Ele...
阅读全文
摘要:This is the classic LCS problem. Since it only requires you to print the maximum length, the code can be optimized to use only O(m) space (seehere).My...
阅读全文
摘要:This is the classic LCS problem. Since it requires you to print one longest common subsequence, just use the O(m*n)-space version here.My accepted cod...
阅读全文
摘要:The Longest Common Subsequence (LCS) problem is as follows:Given two sequences s andt, find the length of the longest sequence r, which is a subsequen...
阅读全文
摘要:The Longest Common Substring (LCS) problem is as follows:Given two strings s and t, find the length of the longest string r, which is a substring of b...
阅读全文
摘要:This problem is a nice extension of the Valid Parentheses problem.There are several ways to solve it. The first idea is also to use a stack. However, ...
阅读全文
摘要:Well, there are two ways to add a open or close parenthesis to the current string.If number of(is less thann, you can add(;If number of)is less than n...
阅读全文
摘要:This is a classic problem of the application of stacks. The idea is, each time we meet a(,{or[, we push it to a stack. If we meet a),}or], we check if...
阅读全文
摘要:Problem Description:Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) ...
阅读全文
摘要:Problem Description:Given a string, find the length of the longest substring T that contains at most 2 distinct characters.For example, Given s =“eceb...
阅读全文
摘要:After reading the quote below the problem, you will be motivated to solve it immediately :-) Well, indeed it is also relative easy. The process of inv...
阅读全文
摘要:This problem is not very intuitive at first glance. However, the final idea should be very self-explanatory. You visit each element in nums, and then ...
阅读全文
摘要:The idea is to find the longest palindromic substring ofsthat begins withs[0]. Then take the remaining susbtring, reverse it and append it to the begi...
阅读全文
摘要:Well, this problem has a O(n^3) solution similar to 3Sum. That is, fix two elements nums[i] and nums[j] (i > fourSum(vector& nums, int target) { 2 ...
阅读全文
摘要:This problem is very similar to 3Sum. You only need to maintain a variable for the sum that is closet to target. Also, some corner cases need to be ha...
阅读全文
摘要:This is an extension of the 2Sum problem. The idea is pretty simple (even no need to use hash). Sort the array and then starting from the first elemen...
阅读全文
摘要:Well, it seems that many people meet the TLE problem. Well, I use a simple trick in my code to aoivd TLE. That is, each time before I try to breaks, I...
阅读全文
摘要:Well, an extension of Remove Duplicates from Sorted Array.The program is fairly similar to that in this solution.1 int removeDuplicates(vector& nu...
阅读全文
摘要:Well, a medium problem. Use two pointers. One points to the curren number and the other points to the last unique number. Once duplicates occur, move ...
阅读全文
摘要:Radix sort is another linear time sorting algorithm. It sorts (using another sorting subroutine) the numbers from their least significant digits to mo...
阅读全文
摘要:Well, this problem is designed for radix sort. For more information about radix sort, Introduction to Algorithms, 3rd edition has some nice examples.H...
阅读全文
摘要:Counting sort is a linear time sorting algorithm. It is used when all the numbers fall in a fixed range. Then it counts the appearances of each number...
阅读全文
摘要:The hints on below the problem have suggested a two-pass solution.Now I will focus on the one-pass solution.The one-pass solution has no mystery. Just...
阅读全文
摘要:This problem gets much trickier than Contains Duplicate and Contains Duplicate II.The basic idea is to maintain a window of k numbers. For each new nu...
阅读全文
摘要:A classic problem of hash set. The unordered_set of C++ is very suitable for this problem.The code is as follows and it should be quite self-explanato...
阅读全文
摘要:Problem Description:Given an array of integers that is alreadysorted in ascending order, find two numbers such that they add up to a specific target n...
阅读全文
摘要:Again, a classic interview question of linked list. Similar to Linked List Cycle, we maintain two pointers fast and slow: fastmove two steps at one ti...
阅读全文
摘要:A classic interview question of linked list. The idea is to maintain two pointers, one move one step at a time and the other move two steps at a time....
阅读全文
摘要:This problem has a long story. There are just too many solutions on the web and it can be studied for a long time before you fully grasp it. Morever, ...
阅读全文
摘要:This is a classic problem for hash table. The basic idea is to maintain a hash table for each element innums, using the element as key and its index (...
阅读全文
摘要:Well, this problem looks easy at first glance. However, to get a bug-free code may be not that easy.The total square is simply equal to the sum of the...
阅读全文
摘要:Well, there many ways to solve this problem. Let's first look at a naive solution.The basic idea is simple. Starting from the first character of the s...
阅读全文
摘要:The key of this problem is that we need not build the tree from scratch. In fact, we can direct obtain its post-order traversal results in a recursive...
阅读全文
摘要:This is a application of the Trie data structure, with minor extension. The critical part in this problem is to count all the words that have a partic...
阅读全文
摘要:A direct applicatin of the heap data structure. Specifically, a max heap is used. The required functions include insertion of a node to the heap and e...
阅读全文
摘要:The idea is to usetwo stacks.Forpush, the first stack records the pushed elements and the second stack recordsallthe minimum (including duplicates) th...
阅读全文
摘要:This problem is an application of the Trie data structure. In the following, it is assumed that you have solvedImplement Trie (Prefix Tree).Now, let's...
阅读全文
摘要:Well, the problem does not aim for an advanced algorithm like KMP but only a clean brute-force algorithm. So we can traverse all the possible starting...
阅读全文
摘要:In this problem, we are asked to divide two integers. However, we are not allowed to use division, multiplication and mod operations. So, what else ca...
阅读全文
摘要:To readncharacters, we first callread4forn / 4times. For example, if we want to read10characters, we will read them in the8 (4 * 2) + 2manner by first...
阅读全文
摘要:Problem Description:Design and implement a TwoSum class. It should support the following operations:addandfind.add- Add the number to an internal data...
阅读全文
摘要:Recently I systematicall review some sorting algorithms, including insertion sort, bubble sort, merge sort and quick sort. I then implement them in C+...
阅读全文
摘要:Recently I reviewed the classic heapsort algorithm and implement it according to contents in Introduction to Algorithms (3rd edition). The heap data s...
阅读全文
摘要:The problem has a nice structure that backtracking naturally fits in. The structure is, given a starting positionidx, we search fromidxtill the end of...
阅读全文
摘要:This problem is somewhat tricky at first glance. However, the final implementation is fairly simple using recursion.The basic idea is, visiting every ...
阅读全文
摘要:Well, this problem desires for the use of dynamic programming. They key to any DP problem is to come up with the state equation. In this problem, we d...
阅读全文
摘要:Recursive (Backtracking)This is a typical problem that can be tackled by backtracking.Since backtracking has a more-or-less similar template, so I do ...
阅读全文
摘要:This problem is similar toBest Time to Buy and Sell Stock. Givenprices, we find the day (denoted asbuy) of the first local minimum and the day (denote...
阅读全文
摘要:This post shares a very simple solution, whose code is rewritten below, just 5 lines :-) 1 class Solution { 2 public: 3 int maxProfit(vector& pric...
阅读全文
摘要:This problem seems to be tricky at first glance. However, if you know Morris traversal, it is just the preorder case of Morris traversal and the code ...
阅读全文
摘要:There are many merge-sort solutions at the forum, but very few quicksort solutions. So I post my accepted quicksort solution here.Well, after reading ...
阅读全文
摘要:This is a typical DP problem. Suppose the minimum path sum of arriving at point(i, j)isS[i][j], then the state equation isS[i][j] = min(S[i - 1][j], S...
阅读全文
摘要:Well, this problem is similar toUnique Paths. The introduction of obstacles only changes the boundary conditions and make some points unreachable (sim...
阅读全文
摘要:This is a fundamental DP problem. First of all, let's make some observations.Since the robot can only move right and down, when it arrives at a point,...
阅读全文
摘要:Well, this problem has a naive solution, which is to sort the array in descending order and return thek-1-th element. However, sorting algorithm gives...
阅读全文
摘要:To be honest, this problem is designed to let you use stacks. However, I don't. In fact, you only need to keep a flagand switch it between falseandtru...
阅读全文
摘要:Well, I do not see what this problem is for. The same code of Binary Tree Level Order Traversal can be used here. The only difference is that we shoul...
阅读全文
摘要:A classic tree traversal problem. I share my two solutions here: BFS and DFS.BFS: 1 vector> levelOrder(TreeNode *root) { 2 vector> levels;...
阅读全文
摘要:This is a fundamental and yet classic problem. I share my three solutions here:Iterative solution using stack ---O(n)time andO(n)space;Recursive solut...
阅读全文
摘要:This is a fundamental and yet classic problem. I share my three solutions here:Iterative solution using stack ---O(n)time andO(n)space;Recursive solut...
阅读全文
摘要:This is a fundamental and yet classic problem. I share my three solutions here:Iterative solution using stack ---O(n)time andO(n)space;Recursive solut...
阅读全文
摘要:Well, the basic idea is fairly straightforward. We maintain a mappingmpfrom a value innumsto its position (index)i. Each time we meet an unseen value,...
阅读全文
摘要:This problem is a little tricky at first glance. However, if you have finished theHouse Robber problem, this problem can simply bedecomposed into two ...
阅读全文
摘要:Well, have you solved thenextPermutationproblem? If so and you have handled the cases of duplicates at that problem, your code can be used in this pro...
阅读全文
摘要:Well, have you solved thenextPermutationproblem? If so, your code can be used in this problem. The idea is fairly simple:sortnumsin ascending order, a...
阅读全文
摘要:Well, in fact the problem of next permutation has been studied long ago. From theWikipedia page, in the 14th century, a man named Narayana Pandita giv...
阅读全文