本文参考了岩之痕的线段树从零开始和线段树详解，原理可以在原文细看，本文主要是对线段树的几个例题进行实现，以备复习
有这样一个场景，给定一个数组，让求任意区间的累加和。
一般有两种算法
但是，如果对其中任意一个数据进行操作，就会对累加和的时间复杂度有影响，第一种只需要修改一个元素，第二种却需要将其后的所有前缀和都进行修改。所以第一种查询费时间修改不费时间，第二种查询不费时间修改费时间。线段树就是为了适应修改和统计操作而设计的。
线段树的原理，就是，将[1,n]分解成若干特定的子区间(数量不超过4*n),然后，将每个区间[L,R]都分解为
少量特定的子区间，通过对这些少量子区间的修改或者统计，来实现快速对[L,R]的修改或者统计。
具体可以参考线段树详解
由此看出，用线段树统计的东西，必须符合区间加法，否则，不可能通过分成的子区间来得到[L,R]的统计结果。
符合区间加法的例子：
不符合区间加法的例子：
1  // 注意！线段树开始是从1开始的，不是0，否则会导致root<<1不是左节点 
1  void PushUp(int root, vector<int>& sum) { 
nums[index] += c
1  void Update(int index, int c, int l, int r, int root, vector<int>& sum) { 
nums[left, right] += c
1  // 下推时必须将统计值更新，子树更新时必须将父节点也上推更新，保证数据一致性 
1  int Query(int left, int right, int l, int r, int root, vector<int>& sum, vector<int>& add) { 
后期更新…
1 

1  // 20190413 
因为最大公因数对于加减没有惰性标记代表性，所以这里采用乘除作为update的参数
update(L,R, c, l, r, root)代表给L到R的所有数都乘以c
1  // 20190413 
待补充。。。
待补充。。。
待补充。。。
待补充。。。
]]>1 

1 

1  １>2>3>4>5>6>7 
1 

1  // 快排版本 
1  // 类似于zeros and ones 
求出数组中最大的子串和，并求出子串
1 

一堆数字如123，324，56怎么拼接得到的值最大。
1 

找出数组中每个数字左边部分（包括自己）最大的数字，然后返回结果数组
1 

1 

一个数组，里面的元素全部初始为0，有以下两种操作：
问到达一个数组目标值得最小操作步数。
1 

1 

1 

1 

1 

1 

1 

0123456791011121314.. 自然数这样顺次排下去，给一个index，找出对应的数字是什么
1 

1  class Solution { 
1  class Solution { 
1  Description 
1 

1 

设计一个短网址系统？短网址生成策略？短网址和长网址的映射关系如何表示？存网址的数据库表太大了怎么办？Sharding后如何分别以长网址或短网址为主key搜索？你觉得这个系统追求的是时间效率还是空间节省？那冗余存储的牺牲值不值得？
1  // 代码待补充 
两个大文件，4g内存，判断两个文件里想同的url
1  /* 
1  输入： 
1 

In a string S of lowercase letters, these letters form consecutive groups of the same character.
For example, a string like S = “abbxxxxzyy” has the groups “a”, “bb”, “xxxx”, “z” and “yy”.
Call a group large if it has 3 or more characters. We would like the starting and ending positions of every large group.
The final answer should be in lexicographic order.
Example 1:
1  Input: "abbxxxxzzy" 
Example 2:
1  Input: "abc" 
Example 3:
1  Input: "abcdddeeeeaabbbcd" 
Note: 1 <= S.length <= 1000
1  class Solution { 
We are given a personal information string S, which may represent either an email address or a phone number.
We would like to mask this personal information according to the following rules:
We define a name to be a string of length ≥ 2 consisting of only lowercase letters az or uppercase letters AZ.
An email address starts with a name, followed by the symbol ‘@’, followed by a name, followed by the dot ‘.’ and followed by a name.
All email addresses are guaranteed to be valid and in the format of “name1@name2.name3“.
To mask an email, all names must be converted to lowercase and all letters between the first and last letter of the first name must be replaced by 5 asterisks ‘*’.
A phone number is a string consisting of only the digits 09 or the characters from the set {‘+’, ‘‘, ‘(‘, ‘)’, ‘ ‘}. You may assume a phone number contains 10 to 13 digits.
The last 10 digits make up the local number, while the digits before those make up the country code. Note that the country code is optional. We want to expose only the last 4 digits and mask all other digits.
The local number should be formatted and masked as “1111”, where 1 represents the exposed digits.
To mask a phone number with country code like “+111 111 111 1111”, we write it in the form “+*1111”. The ‘+’ sign and the first ‘‘ sign before the local number should only exist if there is a country code. For example, a 12 digit phone number mask should start with “+“.
Note that extraneous characters like “(“, “)”, “ “, as well as extra dashes or plus signs not part of the above formatting scheme should be removed.
Return the correct “mask” of the information provided.
Example 1:
1  Input: "LeetCode@LeetCode.com" 
Example 2:
1  Input: "AB@qq.com" 
Example 3:
1  Input: "1(234)567890" 
Example 4:
1  Input: "86(10)12345678" 
1  class Solution { 
Given a positive integer N, how many ways can we write it as a sum of consecutive positive integers?
Example 1:
1  Input: 5 
Example 2:
1  Input: 9 
Example 3:
1  Input: 15 
1  class Solution { 
A character is unique in string S if it occurs exactly once in it.
For example, in string S = “LETTER”, the only unique characters are “L” and “R”.
Let’s define UNIQ(S) as the number of unique characters in string S.
For example, UNIQ(“LETTER”) = 2.
Given a string S with only uppercases, calculate the sum of UNIQ(substring) over all nonempty substrings of S.
If there are two or more equal substrings at different positions in S, we consider them different.
Since the answer can be very large, return the answer modulo 10 ^ 9 + 7.
Example 1:
1  Input: "ABC" 
Example 2:
1  Input: "ABA" 
1  class Solution { 
Leetcode 824
A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to “Goat Latin” (a madeup language similar to Pig Latin.)
The rules of Goat Latin are as follows:
If a word begins with a vowel (a, e, i, o, or u), append “ma” to the end of the word.
For example, the word ‘apple’ becomes ‘applema’.
If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add “ma”.
For example, the word “goat” becomes “oatgma”.
Add one letter ‘a’ to the end of each word per its word index in the sentence, starting with 1.
For example, the first word gets “a” added to the end, the second word gets “aa” added to the end and so on.
Return the final sentence representing the conversion from S to Goat Latin.
Example 1:
1  Input: "I speak Goat Latin" 
Example 2:
1  Input: "The quick brown fox jumped over the lazy dog" 
1  class Solution { 
Some people will make friend requests. The list of their ages is given and ages[i] is the age of the ith person.
Person A will NOT friend request person B (B != A) if any of the following conditions are true:
age[B] <= 0.5 * age[A] + 7
age[B] > age[A]
age[B] > 100 && age[A] < 100
Otherwise, A will friend request B.
Note that if A requests B, B does not necessarily request A. Also, people will not friend request themselves.
How many total friend requests are made?
Example 1:
1  Input: [16,16] 
Example 2:
1  Input: [16,17,18] 
Example 3:
1  Input: [20,30,100,110,120] 
1  class Solution { 
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
1  Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7] 
1  class Solution { 
In a 2D grid of 0s and 1s, we change at most one 0 to a 1.
After, what is the size of the largest island? (An island is a 4directionally connected group of 1s).
Example 1:
Input: [[1, 0], [0, 1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
Example 2:
Input: [[1, 1], [1, 0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
Example 3:
Input: [[1, 1], [1, 1]]
Output: 4
Explanation: Can’t change any 0 to 1, only one island with area = 4.
本来思路是并查集加BFS，但是由于并查集写的代码太长导致时间不够用
1  class Solution { 
Leetcode 821
Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.
Example 1:
1  Input: S = "loveleetcode", C = 'e' 
1  class Solution { 
On a table are N cards, with a positive integer printed on the front and back of each card (possibly different).
We flip any number of cards, and after we choose one card.
If the number X on the back of the chosen card is not on the front of any card, then this number X is good.
What is the smallest number that is good? If no number is good, output 0.
Here, fronts[i] and backs[i] represent the number on the front and back of card i.
A flip swaps the front and back numbers, so the value on the front is now on the back and vice versa.
Example:
1  Input: fronts = [1,2,4,4,7], backs = [1,3,4,1,3] 
1  class Solution { 
Leetcode 820
Given a list of words, we may encode it by writing a reference string S and a list of indexes A.
For example, if the list of words is [“time”, “me”, “bell”], we can write it as S = “time#bell#” and indexes = [0, 2, 5].
Then for each index, we will recover the word by reading from the reference string from that index until we reach a “#” character.
What is the length of the shortest reference string S possible that encodes the given words?
Example:
1  Input: words = ["time", "me", "bell"] 
1  class Solution { 
Given an array of unique integers, each integer is strictly greater than 1.
We make a binary tree using these integers and each number may be used for any number of times.
Each nonleaf node’s value should be equal to the product of the values of it’s children.
How many binary trees can we make? Return the answer modulo 10 ** 9 + 7.
Example 1:
1  Input: A = [2, 4] 
Example 2:
1  Input: A = [2, 4, 5, 10] 
1  class Solution { 
Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn’t banned, and that the answer is unique.
Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase.
Example:
1  Input: 
1  class Solution { 
We are given head, the head node of a linked list containing unique integer values.
We are also given the list G, a subset of the values in the linked list.
Return the number of connected components in G, where two values are connected if they appear consecutively in the linked list.
Example 1:
1  Input: 
Example 2:
1  Input: 
1  /** 
We had some 2dimensional coordinates, like “(1, 3)” or “(2, 0.5)”. Then, we removed all commas, decimal points, and spaces, and ended up with the string S. Return a list of strings representing all possibilities for what our original coordinates could have been.
Our original representation never had extraneous zeroes, so we never started with numbers like “00”, “0.0”, “0.00”, “1.0”, “001”, “00.01”, or any other number that can be represented with less digits. Also, a decimal point within a number never occurs without at least one digit occuring before it, so we never started with numbers like “.1”.
The final answer list can be returned in any order. Also note that all coordinates in the final answer have exactly one space between them (occurring after the comma.)
1  Example 1: 
1  class Solution { 
Your car starts at position 0 and speed +1 on an infinite number line. (Your car can go into negative positions.)
Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse).
When you get an instruction “A”, your car does the following: position += speed, speed *= 2.
When you get an instruction “R”, your car does the following: if your speed is positive then speed = 1 , otherwise speed = 1. (Your position stays the same.)
For example, after commands “AAR”, your car goes to positions 0>1>3>3, and your speed goes to 1>2>4>1.
Now for some target position, say the length of the shortest sequence of instructions to get there.
1  Example 1: 
1  class Solution { 
之前的项目中用到了FTRL，在最近的交流中经常被问及这方面的相关基础，发现之前对在线学习的基础知识掌握不全面，以及对OGD和SGD等效性没有理论依据，这里作为总结。
本文参考资料losteng的csdn和雷天琪的回答
在线学习算法强调的是训练的实时性，面向流式数据，每次训练不使用全量数据，而是以之前训练好的参数为基础，每次利用一个样本更新一次模型，是属于增量学习的一部分，从而快速更新模型，提高模型的时效性。
统计学习的先验假设是数据存在自己一定的分布，我们的目的是寻找与实际分布距离最小的策略来泛化未知的结果。数据由真实模型产生，如果能有无限数据、并在包含有真实模型的空间里求解，也许我们能算出真是模 型。但实际上我们只有有限的有噪音的数据，这又限制我们只能使用相对简单的模型。所以，理想的算法是能够用不多的数据来得到一个不错的模型。
离线学习算法强调的是数据中不断训练已有的模型，不断迭代达到真实的数据分布，在训练过程中，所有数据都是可见的，目标是一定的（就是最终的那个真实分布），其中可以采用不同的更新策略和采样策略，所以有了批量梯度下降和随机梯度下降等算法。
但是，在线学习算法的关注点是不同的，在线学习算法的限制条件是只能看到过去的数据和当前的数据，看不到未来的数据，所以我们训练的策略可能是任意的数据分布，通过不断的训练可能颠覆之前的训练结果，所以在线学习甚至是为了破坏我们之前的策略精心设计的。
在线学习关注点在于，追求对所知道的所有知识所能设计最优的策略，那么同这个最优的策略的差距成为后悔（regret）:后悔没有从一开始就选择这个策略，当然，我们希望的是，随着时间的增加，这个差异会不断的变小。因为我们不对数据进行任何假设，所以策略是否完美并不是我们关心的（比如回答所有问题），我们追求的是，没有后悔（noregret）
梯度下降可以分成两种模式，batch模式和delta模式。batch模式的时效性比delta模式要低一些。分析一下batch模式，比如昨天及昨天的数据训练成了模型M，那么今天的每一条训练数据在训练过程中都会更新一次模型M，从而生成今天的模型M1。
batch学习可以认为是离线学习算法，强调的是每次训练都需要使用全量的样本，因而可能会面临数据量过大的问题。一般进行多轮迭代来向最优解靠近。online learning没有多轮的概念，如果数据量不够或训练数据不够充分，通过copy多份同样的训练数据来模拟batch learning的多轮训练也是有效的方法。
delta模式可以认为是在线学习算法，没有多轮的概念，如果数据量不够或训练数据不够充分，通过copy多份同样的训练数据来模拟batch learning的多轮训练也是有效的方法。所以，OGD和SGD都属于在线学习算法，因为每次更新模型只用一个样本。SGD则每次只针对一个观测到的样本进行更新。通常情况下，SGD能够比GD“更快”地令 逼近最优值。当样本数 特别大的时候，SGD的优势更加明显，并且由于SGD针对观测到的“一条”样本更新 ，很适合进行增量计算，实现梯度下降的Online模式（OGD, OnlineGradient Descent）。
本章只是简单介绍，如果想要深入了解在线凸优化（OCO），强烈推荐阅读Elad Hazand的著作和Zinkevich的Paper
聊到在线学习算法通常会说到专家系统，在$t$时刻专家$i$的损失是$\ell_t(e^i)$，于是这个时刻Weighted Majority（WM）损失的期望是$\sum_{i=1}^m w_t^i\ell_t(e^i)$，是关于这m个专家的损失的一个线性组合（因为权重$w_t^i$关于$i$的和为1，所以实际上是在一个simplex上）。将专家在$t$时刻的损失看成是这个时候进来的数据点，于是我们便在这里使用了一个线性的损失函数。
WM的理论证明可以参考Littlestone 94,Freund 99，虽然在上个世纪已经完成，但是将其理论拓展到一般的凸的函数还是在03年由Zinkevich完成的。
Zinkevich提出的算法很简单，在时刻t做两步操作，首先利用当前得到数据对$h_t$进行一次梯度下降得到$h_{t+1}$，如果新的$h_{t+1}$不在$\mathcal{H}$中，那么将其投影进来：
$$\displaystyle h_{t+1}=\Pi_{\mathcal{H}}(h_t\eta_t\nabla\ell_t(h_t))$$
这里$\nabla\ell_t(h_t)$是$\ell_t(h_t)$关于$h_t$的导数（如果导数不唯一，就用次导数），$\eta_t$是学习率，$\Pi_{\mathcal{H}}(\cdot)$是投影子，其将不在$\mathcal{H}$中的向量$x$投影成一个与$x$最近的但在$\mathcal{H}$中的向量（如果$x$已经在$\mathcal{H}$中了，那就不做任何事），用公式表达就是$\Pi_{\mathcal{H}}(x)=\arg\min_{y\in\mathcal{H}}xy$。此算法通常被称之为 Online Gradient Descent。
先来啰嗦几句其与离线梯度下降的区别。在离线的情况下，我们知道所有数据，所以能计算得到整个目标函数的梯度，从而朝最优解 迈出坚实的一步。而在online设定下，我们只根据当前的数据来计算一个梯度，其很可能与真实目标函数的梯度有一定的偏差。我们能保证的只是会减小的值，而对别的项的减少程度是未知的。当然，我们还是一直在朝目标前进，只是可能要走点弯路。
那online的优势在哪里呢？其关键是每走一步只需要看一下当前的一个数据，所以代价很小。而offline的算法每走一个要看下所有数据来算一 个真实梯度，所以代价很大。假定有100个数据，offline走10步就到最优，而online要100步才能到。但这样offline需要看1000 个数据，而online只要看100个数据，所以还是online代价小。
在这里，$\mathcal{H}$的作用是什么呢？记得在ML中的目标函数通常是损失+罚$\ell(h)+\lambda f(h)$的形式。例如ridge regression就是平方误差+$\ell_2$罚，lasso是平方误差+$\ell_1$罚，SVM是hinge loss+$\ell_2$罚。最小化这个目标函数可以等价于在$f(h)\le\delta$的限制下最小化$\ell(h)$。$\lambda$和$\delta$是一一对应的关系。实际上$f(h)\le\delta$就是定义了一个凸子空间，例如使用$\ell_2$罚时就是一个半径为$\delta$的球。所以，Online Gradient Descent可以online的解这一类目标函数，只是对于不同的罚选择不同的投影子。
下面是理论分析。记投影前的 $\tilde h_{t+1} = h_t\eta_t\nabla\ell_t(h_t)$，以及offline最优解$h^=\arg\min_{h\in\mathcal{H}}\sum_{t=1}^T\ell_t(h)$ 。因为$ \mathcal{H} $是凸的且 $ h^ $ 在其中，所以对 $ \tilde h_{t+1} $ 投影只会减少其与 $ h^ $ 的距离，既 $ h_{t+1}h^\le\tilde h_{t+1}h^* $ 。记 $ \nabla_t=\nabla \ell_t(h_t) $ ，注意到
$$\displaystyle \tilde h_{t+1}h^^2=h_th^^2+\eta_t^2\nabla_t^22\eta_t\langle\nabla_t,h_th^*\rangle.$$
由于$\ell_t$是凸的，所以有
$$\displaystyle \ell_t(h_t)\ell_t(h^)\le \langle\nabla_t,h_th^\rangle \le \frac{1}{2\eta_t}\big(h_th^^2  h_{t+1}h^^2\big) + \frac{\eta_t}{2}\nabla_t^2.$$
取固定的$\eta_t=\eta$，对$t$进行累加就有$R(T)\le \frac{1}{2\eta}w_1w^*^2+\frac{\eta}{2}\sum_{t=1}^T\nabla_t^2$。记$\mathcal{H}$的直径为$D$，且对所有$t$有$\nabla_t\le L$成立（既Lipschitz常数为$L$），再取$\eta=\frac{D}{L\sqrt{T}}$，那么
$$\displaystyle R(T)\le LD\sqrt{T}.$$
这个bound可以通过设置变动的学习率$\eta_t$加强。
SGD算法的迭代计算公式如下：
其中 t 为迭代轮数，w是模型参数，g是loss function关于w的梯度，而η是学习率。
FTRL算法的迭代算公式如下：
其中 t 为迭代轮数，w是模型参数，σs定义成
λ1是L1正则化系数。在公式2中，arg min算子的内容中由3项组成，如果我们去掉最后面的L1正则化项，公式2就变成下面的公式3：
（3）式子在换个形式后就等价于梯度下降公式。
以下是推导过程：
首先，我们要求公式3中的最小值，我们可以对其求导，得到
令上面的求导公式等于0就得到极值，极值正是Wt+1：
将含有wt+1的项放到等号左边，剩下的放在右边，得到公式6：
进一步化简得到公式7：
用 t1 替换 t，得到公式8：
用公式7减去公式8，即式子的左边右边同时减去，得到公式9：
把σt用ηt表示，得到公式10：
对公式10化简即可得到公式1：
通过上面的推导证明，我们看到公式3与公式1确实等价。
]]>A rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) are the coordinates of its bottomleft corner, and (x2, y2) are the coordinates of its topright corner.
Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.
Given two (axisaligned) rectangles, return whether they overlap.
Example 1:
1  Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3] 
Example 2:
1  Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1] 
1  class Solution { 
There are N dominoes in a line, and we place each domino vertically upright.
In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left.
Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
Given a string “S” representing the initial state. S[i] = ‘L’, if the ith domino has been pushed to the left; S[i] = ‘R’, if the ith domino has been pushed to the right; S[i] = ‘.’, if the ith domino has not been pushed.
Return a string representing the final state.
Example 1:
1  Input: ".L.R...LR..L.." 
Example 2:
1  Input: "RR.L" 
1  class Solution { 
Alice plays the following game, loosely based on the card game “21”.
Alice starts with 0 points, and draws numbers while she has less than K points. During each draw, she gains an integer number of points randomly from the range [1, W], where W is an integer. Each draw is independent and the outcomes have equal probabilities.
Alice stops drawing numbers when she gets K or more points. What is the probability that she has N or less points?
Example 1:
1  Input: N = 10, K = 1, W = 10 
Example 2:
1  Input: N = 6, K = 1, W = 10 
Example 3:
1  Input: N = 21, K = 17, W = 10 
1  class Solution { 
Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y.
For example, “tars” and “rats” are similar (swapping at positions 0 and 2), and “rats” and “arts” are similar, but “star” is not similar to “tars”, “rats”, or “arts”.
Together, these form two connected groups by similarity: {“tars”, “rats”, “arts”} and {“star”}. Notice that “tars” and “arts” are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.
We are given a list A of strings. Every string in A is an anagram of every other string in A. How many groups are there?
Example 1:
1  Input: ["tars","rats","arts","star"] 
1  // 并查集 
Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].
To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0].
Example 1:
1  Input: [[1,1,0],[1,0,1],[0,0,0]] 
Example 2:
1  Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] 
1  class Solution { 
To some string S, we will perform some replacement operations that replace groups of letters with new ones (not necessarily the same size).
Each replacement operation has 3 parameters: a starting index i, a source word x and a target word y. The rule is that if x starts at position i in the original string S, then we will replace that occurrence of x with y. If not, we do nothing.
For example, if we have S = “abcd” and we have some replacement operation i = 2, x = “cd”, y = “ffff”, then because “cd” starts at position 2 in the original string S, we will replace it with “ffff”.
Using another example on S = “abcd”, if we have both the replacement operation i = 0, x = “ab”, y = “eee”, as well as another replacement operation i = 2, x = “ec”, y = “ffff”, this second operation does nothing because in the original string S[2] = ‘c’, which doesn’t match x[0] = ‘e’.
All these operations occur simultaneously. It’s guaranteed that there won’t be any overlap in replacement: for example, S = “abc”, indexes = [0, 1], sources = [“ab”,”bc”] is not a valid test case.
Example 1:
1  Input: S = "abcd", indexes = [0,2], sources = ["a","cd"], targets = ["eee","ffff"] 
Example 2:
1  Input: S = "abcd", indexes = [0,2], sources = ["ab","ec"], targets = ["eee","ffff"] 
1  class Solution { 
Two images A and B are given, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.)
We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the overlap of this translation is the number of positions that have a 1 in both images.
(Note also that a translation does not include any kind of rotation.)
What is the largest possible overlap?
Example 1:
1  Input: A = [[1,1,0], 
1  class Solution { 
An undirected, connected tree with N nodes labelled 0…N1 and N1 edges are given.
The ith edge connects nodes edges[i][0] and edges[i][1] together.
Return a list ans, where ans[i] is the sum of the distances between node i and all other nodes.
Example 1:
1  Input: N = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]] 
1  // BFS 超时版本.... 
1  // 后用dfs保存中间状态AC 
Given a singly linked list, return a random node’s value from the linked list. Each node must have the same probability of being chosen.
Follow up:
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?
Example:
1  // Init a singly linked list [1,2,3]. 
1  /** 
Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.
Example:
1  int[] nums = new int[] {1,2,3,3,3}; 
1  class Solution { 
You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].
Example:
1  Input: [5,2,6,1] 
1  // 此题先用二分查找树实现，线段树实现方法之后正在更新 
1  int gcd(int a, int b) { 
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn’t one, return 0 instead.
Example:
1  Input: s = 7, nums = [2,3,1,2,4,3] 
1  class Solution { 
1 

Return the length of the shortest, nonempty, contiguous subarray of A with sum at least K.
If there is no nonempty subarray with sum at least K, return 1.
Example 1:
1  Input: A = [1], K = 1 
Example 2:
1  Input: A = [1,2], K = 4 
Example 3:
1  Input: A = [2,1,2], K = 3 
1 

1 

快排的优化可以参考此处文献
基准随机化算法
1 

将前后中间三个数取中值作为标兵元素
验证地址Leetcode 215
1 

贪心算法，最小类似
1 

1 

Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a nonnegative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
1  Input: 4 
Example 2:
1  Input: 8 
1  class Solution { 
1 

1 

Implement pow(x, n), which calculates x raised to the power n (x^{n}).
1  Input: 2.00000, 10 
1  class Solution { 
矩阵乘法还可以做dp优化，之后更新….
1 

对于数字全排列可以用这种方法
1  string getPermutation(int n, int k) { 
数字可以用上面的方法，但是对于字母来说就不行了，因为long long也存不下所有全排列的种类数
第二个思路是使用nextPermutation，此函数的原理是
nextPermutation的头文件是algorithm
1  string getPermutation(int n, int k) { 
一个树形的图，要遍历其中k个节点，最少需要走多少步
1 

表达式求值
1 

寻找能使数组跷跷板平衡的支点有几个
1 

给定一组数，表示他所在组的大小，输出一个数组，同一分组的在一起，数组保证字典序最小
1 

题目：给定一个状态转移图，和一个目标字符集合
M=
 A B C 
—:–::–::–:
A B,C C A 
B A,C C C 
C A A A,B 
S={A,B,C}
每两个字符可以转换成一个字符，例如AAB可以转成BC，判断是否能最后转化成目标集合中的字符
1 

这里总结一些DP类型的题目，因为贪心一定程度可以认为是一维的DP，所以也做总结
Given an array of nonnegative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Example 1:
1  Input: [2,3,1,1,4] 
Example 2:
1  Input: [3,2,1,0,4] 
1  class Solution { 
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
Note: The algorithm should run in linear time and in O(1) space.
Example 1:
1  Input: [3,2,3] 
Example 2:
1  Input: [1,1,1,3,3,2,2,2] 
1  class Solution { 
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.
Note:
The number of people is less than 1,100.
Example
1  Input: 
1  class Solution { 
There are a number of spherical balloons spread in twodimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it’s horizontal, ycoordinates don’t matter and hence the xcoordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.
An arrow can be shot up exactly vertically from different points along the xaxis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.
Example:
1  Input: 
1  class Solution { 
Given a nonnegative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.
Note:
Example 1:
1  Input: num = "1432219", k = 3 
Example 2:
1  Input: num = "10200", k = 1 
Example 3:
1  Input: num = "10", k = 2 
1  class Solution { 
1 

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station’s index if you can travel around the circuit once in the clockwise direction, otherwise return 1.
Note:
Example 1:
1  Input: 
Example 2:
1  Input: 
1  class Solution { 
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.
Example 1:
1  Input: 2 
Example 2:
1  Input: 5 
1  class Solution { 
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of nonnegative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
Example 1:
1  Input: [2,3,2] 
Example 2:
1  Input: [1,2,3,1] 
1  class Solution { 
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies:
Si % Sj = 0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
Example 1:
1  Input: [1,2,3] 
Example 2:
1  Input: [1,2,4,8] 
1  class Solution { 
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 complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
1  Input: [1,2,3,0,2] 
1  class Solution { 
1 

Given a nonempty string s and a dictionary wordDict containing a list of nonempty words, determine if s can be segmented into a spaceseparated sequence of one or more dictionary words.
Note:
Example 1:
1  Input: s = "leetcode", wordDict = ["leet", "code"] 
Example 2:
1  Input: s = "applepenapple", wordDict = ["apple", "pen"] 
Example 3:
1  Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] 
1  class Solution { 
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,3,5,7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Examples:
1  Input: [1,7,4,9,2,5] 
1  class Solution { 
A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
1  For example, these are arithmetic sequence: 
Example:
1  A = [1, 2, 3, 4] 
1  class Solution { 
Given an input string (s) and a pattern (p), implement regular expression matching with support for ‘.’ and ‘*’.
1  '.' Matches any single character. 
Note:
Example 1:
1  Input: 
Example 2:
1  Input: 
Example 3:
1  Input: 
Example 4:
1  Input: 
Example 5:
1  Input: 
1  class Solution { 
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for ‘?’ and ‘*’.
‘?’ Matches any single character.
‘*’ Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Note:
s could be empty and contains only lowercase letters az.
p could be empty and contains only lowercase letters az, and characters like ? or *.
Example 1:
1  Input: 
Example 2:
1  Input: 
Example 3:
1  Input: 
Example 4:
1  Input: 
Example 5:
1  Input: 
1  class Solution { 
A sequence X_1, X_2, …, X_n is fibonaccilike if:
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonaccilike subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
1  Input: [1,2,3,4,5,6,7,8] 
Example 2:
1  Input: [1,3,7,11,12,14,18] 
1  class Solution { 
In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue.
For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s.
Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. Each 0 and 1 can be used at most once.
Note:
Example 1:
1  Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3 
Example 2:
1  Input: Array = {"10", "0", "1"}, m = 1, n = 1 
1  class Solution { 
Given a nonempty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Note:
Example 1:
1  Input: [1, 5, 11, 5] 
Example 2:
1  Input: [1, 2, 3, 5] 
1  class Solution { 
1 

1 

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.
1  Example 1: 
1  class Solution { 
Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]….
1  Example 1: 
1  class Solution { 
Follow Up: Can you do it in O(n) time and/or inplace with O(1) extra space?
主要思想是先用快速找到中间的数，然后利用快搜中partition的思想将前半数据放到奇数位上，后半段的数放入偶数位，解释可以参考Discuss
1  void wiggleSort(vector<int>& nums) { 
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
1  Input: [100, 4, 200, 1, 3, 2] 
1  class Solution { 
BFS因为占用的空间比较大且一般时间比较长，所以经常用在需要全部数据都要检索的题目上，一般的类型包括：
There are a total of n courses you have to take, labeled from 0 to n1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
1  Example 1: 
1  class Solution { 
For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.
Format
The graph contains n nodes which are labeled from 0 to n  1. You will be given the number n and a list of undirected edges (each edge is a pair of labels).
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
Example 1 :
1  Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]] 
Example 2 :
1  Input: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]] 
1  class Solution { 
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary [“JFK”, “LGA”] has a smaller lexical order than [“JFK”, “LGB”].
All airports are represented by three capital letters (IATA code).
You may assume all tickets form at least one valid itinerary.
Example 1:
1  Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]] 
Example 2:
1  Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] 
1  // 欧拉环路 
Given a binary tree
1  struct TreeLinkNode { 
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
You may only use constant extra space.
Recursive approach is fine, implicit stack space does not count as extra space for this problem.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
Example:
1  Given the following perfect binary tree, 
1  /** 
Given a nonempty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parentchild connections. The path must contain at least one node and does not need to go through the root.
Example 1:
1  Input: [1,2,3] 
Example 2:
1  Input: [10,9,20,null,null,15,7] 
1  /** 
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.
Example 1:
1  Input: root = [3,1,4,null,2], k = 1 
Example 2:
1  Input: root = [5,3,6,2,4,null,null,1], k = 3 
1  /** 
Given n pairs of parentheses, write a function to generate all combinations of wellformed parentheses.
For example, given n = 3, a solution set is:
1  [ 
1  class Solution { 
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the “root.” Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that “all houses in this place forms a binary tree”. It will automatically contact the police if two directlylinked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 1:
1  Input: [3,2,3,null,3,null,1] 
Example 2:
1  Input: [3,4,5,1,3,null,1] 
1  /** 
Given an encoded string, return it’s decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are wellformed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won’t be input like 3a or 2[4].
Examples:
1  s = "3[a]2[bc]", return "aaabcbc". 
1  class Solution { 
Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.
Example 1:
1  Input: [1,1,2,2,2] 
Example 2:
1  Input: [3,3,3,3,4] 
1  class Solution { 
follow up: Partition to K Equal Sum Subsets
Given an array of integers nums and a positive integer k, find whether it’s possible to divide this array into k nonempty subsets whose sums are all equal.
Example 1:
1  Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4 
1  class Solution { 
DescriptionHintsSubmissionsDiscussSolution
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
1  Input: [1,2,2] 
1  class Solution { 
DescriptionHintsSubmissionsDiscussSolution
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
1  board = 
1  class Solution { 
Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wraparound is not allowed).
Example 1:
1  Input: nums = 
Example 2:
1  Input: nums = 
1  class Solution { 
Given a nonempty string s and a dictionary wordDict containing a list of nonempty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:
1  Input: 
Example 2:
1  Input: 
Example 3:
1  Input: 
1  class Solution { 
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters az or .. A . means it can represent any one letter.
Example:
1  addWord("bad") 
1  struct TrieNode { 
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary [“JFK”, “LGA”] has a smaller lexical order than [“JFK”, “LGB”].
All airports are represented by three capital letters (IATA code).
You may assume all tickets form at least one valid itinerary.
Example 1:
1  Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]] 
Example 2:
1  Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] 
1  // dfs 版本 
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
1  inorder = [9,3,15,20,7] 
1  /** 
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
1  Input: "25525511135" 
1  class Solution { 
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +,  and *.
Example 1:
1  Input: "211" 
Example 2:
1  Input: "2*34*5" 
1  class Solution { 
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
1  Input: "aab" 
1  class Solution { 
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
1  Input: [1,1,2] 
1  class Solution { 
The set [1,2,3,…,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
1  "123" 
Note:
Given n will be between 1 and 9 inclusive.
Given k will be between 1 and n! inclusive.
Example 1:
1  Input: n = 3, k = 3 
Example 2:
1  Input: n = 4, k = 9 
1  class Solution { 
1  // next permutation 版本 
二分查找一般用来简化查找逻辑，将O(n)降低成O(logn)，但是由于左右边界更新的细节比较多，每个题都需要单独推导分析
Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.
Example 1:
1  Input: [3,0,1] 
Example 2:
1  Input: [9,6,4,2,3,5,7,0,1] 
1  // 除此之外还有循环替换算法以及位操作算法 
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Example 1:
1  Input: 
Example 2:
1  Input: 
1  // 线性扫描 
1  // 二分法 
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Example:
1  Consider the following matrix: 
1  // 其实也就是二分查找的思想，右侧路过的值就是查找空间的上界，左侧路过的值是下界 
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
1  matrix = [ 
1  // upper_bound是找到大于该值的第一个数，lower_bound是找到大于等于该值的第一个数 
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
1  nums1 = [1, 3] 
Example 2:
1  nums1 = [1, 2] 
1  typedef vector<int>::iterator Iter; 
Given a set of intervals, for each of the interval i, check if there exists an interval j whose start point is bigger than or equal to the end point of the interval i, which can be called that j is on the “right” of i.
For any interval i, you need to store the minimum interval j’s index, which means that the interval j has the minimum start point to build the “right” relationship for interval i. If the interval j doesn’t exist, store 1 for the interval i. Finally, you need output the stored value of each interval as an array.
Note:
You may assume the interval’s end point is always bigger than its start point.
You may assume none of these intervals have the same start point.
Example 1:
1  Input: [ [1,2] ] 
Example 2:
1  Input: [ [3,4], [2,3], [1,2] ] 
Example 3:
1  Input: [ [1,4], [2,3], [3,4] ] 
1  /** 
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [1, 1].
Example 1:
1  Input: nums = [5,7,7,8,8,10], target = 8 
Example 2:
1  Input: nums = [5,7,7,8,8,10], target = 6 
1  class Solution { 
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.
Example 1:
1  Input: [3,4,5,1,2] 
Example 2:
1  Input: [4,5,6,7,0,1,2] 
1  class Solution { 
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return 1.
You may assume no duplicate exists in the array.
Your algorithm’s runtime complexity must be in the order of O(log n).
Example 1:
1  Input: nums = [4,5,6,7,0,1,2], target = 0 
Example 2:
1  Input: nums = [4,5,6,7,0,1,2], target = 3 
1  class Solution { 
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example 1:
1  Input: nums = [2,5,6,0,0,1,2], target = 0 
Example 2:
1  Input: nums = [2,5,6,0,0,1,2], target = 3 
Follow up:
1  class Solution { 
Koko loves to eat bananas. There are N piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in H hours.
Koko can decide her bananasperhour eating speed of K. Each hour, she chooses some pile of bananas, and eats K bananas from that pile. If the pile has less than K bananas, she eats all of them instead, and won’t eat any more bananas during this hour.
Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back.
Return the minimum integer K such that she can eat all the bananas within H hours.
Example 1:
1  Input: piles = [3,6,7,11], H = 8 
Example 2:
1  Input: piles = [30,11,23,4,20], H = 5 
Example 3:
1  Input: piles = [30,11,23,4,20], H = 6 
Note:
1  // 二分答案，类似于求绝对值差值第K大那道题 
还未归类的题目放到这里，此部分待编辑
在数组中的两个数字，如果前面一个数字大于后面的数字，则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
思路可以参考牛客网
1  class Solution { 
这里总结一些leetcode上比较经典的与数据结构相关的例题与思路，因为部分数据结构更偏向与搜索或贪心类型，该类题目就不再本部分总结…
字符串和数组是比较典型的线性表结构，由于比较好访问，所以通常会在该类数据结构上设计搜索和dp类型的题目。
搜索和动规类型的题目会另做讨论，本部分主要总结比较典型反映字符串和数组属性的题目，例如线性表操作或双指针等。
表达式求值是一类比较考察细节的题目，一般会涉及括号，四则运算，小数和空格，所以在写的时候要注意思路清晰，以下提供一个模板：
1 

1  Implement a basic calculator to evaluate a simple expression string. 
1  class Solution { 
1  Implement a basic calculator to evaluate a simple expression string. 
1  class Solution { 
Leetcode 43字符串乘法
Given two nonnegative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
1  Example 1: 
1  class Solution { 
Leetcode 445无符号字符串加法
You are given two nonempty linked lists representing two nonnegative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
1  Example: 
1  /** 
1 

双指针有两种用法，第一种是用于更新原字符串，另一种是用于搜索。一般而言，快指针不光可以表示原本字符串上的位置，同时还可以表示扩展字符串后的位置。
Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.
Example 1:
1  Input: 
Example 2:
1  Input: 
1  class Solution { 
1  Given an input string, reverse the string word by word. 
1  class Solution { 
1  Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). 
1  class Solution { 
An encoded string S is given. To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken:
If the character read is a letter, that letter is written onto the tape.
If the character read is a digit (say d), the entire current tape is repeatedly written d1 more times in total.
Now for some encoded string S, and an index K, find and return the Kth letter (1 indexed) in the decoded string.
1  Example 1: 
1  class Solution { 
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
1  Example 1: 
1  // 最长回文数的最常见算法为O(n2)，还有优化版本，但是需要讲解数学逻辑，之后更新... 
此部分会不断更新…
1  Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither. 
1  // 此方法主要是用于练习字符串处理，如果想要寻找更加高效的算法请在leetcode discuss区寻找 
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
Formally the function should:
Return true if there exists i, j, k
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n1 else return false.
Note: Your algorithm should run in O(n) time complexity and O(1) space complexity.
1  Example 1: 
1  class Solution { 
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
1  Example 1: 
Note: The length of the given binary array will not exceed 50,000.
1  class Solution { 
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of 228 to 228  1 and the result is guaranteed to be at most 2^{31}  1.
1  Example: 
1  class Solution { 
Given a list of non negative integers, arrange them such that they form the largest number.
1  Example 1: 
Note: The result may be very large, so you need to return a string instead of an integer.
1  class Solution { 
Given an unsorted integer array, find the smallest missing positive integer.
1  Example 1: 
1  class Solution { 
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
1  Example 1: 
1  class Solution { 
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
1  Example: 
1  class Solution { 
Given a string, find the length of the longest substring without repeating characters.
1  Example 1: 
1  class Solution { 
HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢？例如:{6,3,2,7,15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组，返回它的最大连续子序列的和，你会不会被他忽悠住？(子向量的长度至少是1)
1  class Solution { 
牛客网
因为此题细节较多，为了多加练习，在此处也做整理
求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数？为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数（从1 到 n 中1出现的次数）。
1  class Solution { 
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn’t one, return 0 instead.
1  Example: 
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
1  class Solution { 
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
1  Example: 
1  class Solution { 
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
1  Example: 
The sum that is closest to the target is 2. (1 + 2 + 1 = 2).
1  // 3Sum的扩展版本 
把只包含质因子2、3和5的数称作丑数（Ugly Number）。例如6、8都是丑数，但14不是，因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
1  class Solution { 
Write a program to find the nth super ugly number.
Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k.
1  Example: 
1  class Solution { 
Given a sorted array nums, remove the duplicates inplace such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array inplace with O(1) extra memory.
1  Example 1: 
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
1  // nums is passed in by reference. (i.e., without making a copy) 
1  class Solution { 
Given n nonnegative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
1  Example: 
1  class Solution { 
给定一个数组A[0,1,…,n1],请构建一个数组B[0,1,…,n1],其中B中的元素B[i]=A[0]A[1]…A[i1]A[i+1]…A[n1]。不能使用除法。
1  class Solution { 
队列通常的应用一般包括单调队列等，这里只列出一部分单调队列题目，之后不断补充…
Return the length of the shortest, nonempty, contiguous subarray of A with sum at least K.
If there is no nonempty subarray with sum at least K, return 1.
1  Example 1: 
1  class Solution { 
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
1  Example: 
Note:
You may assume k is always valid, 1 ≤ k ≤ input array’s size for nonempty array.
Follow up:
Could you solve it in linear time?
1  class Solution { 
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key)  Get the value (will always be positive) of the key if the key exists in the cache, otherwise return 1.
put(key, value)  Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
Follow up:
Could you do both operations in O(1) time complexity?
1  Example: 
list是stl的双端链表，链表指针可以用O(1)时间删除，但是随机访问时间慢
1  typedef list<int>::iterator Iter; 
Sort a linked list using insertion sort.
Algorithm of Insertion Sort:
Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
It repeats until no input elements remain.
1  Example 1: 
1  /** 
Sort a linked list in O(n log n) time using constant space complexity.
1  Example 1: 
1  /** 
1  // 快排版本 
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
1  Example 1: 
1  /** 
Given a singly linked list L: L0→L1→…→Ln1→Ln,
reorder it to: L0→Ln→L1→Ln1→L2→Ln2→…
You may not modify the values in the list’s nodes, only nodes itself may be changed.
1  Example 1: 
1  /** 
Reverse a linked list from position m to n. Do it in onepass.
Note: 1 ≤ m ≤ n ≤ length of list.
1  Example: 
1  /** 
Given a sequence of n integers a1, a2, …, an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.
Note: n will be less than 15,000.
1  Example 1: 
1  class Solution { 
Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversingorder next in the array, which means you could search circularly to find its next greater number. If it doesn’t exist, output 1 for this number.
1  Example 1: 
1  class Solution { 
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
1  /** 
One way to serialize a binary tree is to use preorder traversal. When we encounter a nonnull node, we record the node’s value. If it is a null node, we record using a sentinel value such as #.
1  _9_ 