## 002* Median of Two Sorted Arrays

There are two sorted arrays A and B 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)).

``` class Solution:
def findKth(self, A, A_start, B, B_start, k):
if A_start >= len(A):
return B[B_start + k - 1]
if B_start >= len(B):
return A[A_start + k - 1]
if k == 1:
return min(A[A_start], B[B_start])
A_key = 0x3f3f3f3f
if A_start + k / 2 - 1 < len(A):
A_key = A[A_start + k / 2 - 1]
B_key = 0x3f3f3f3f
if B_start + k / 2 - 1 < len(B):
B_key = B[B_start + k / 2 - 1]
if A_key < B_key:
return self.findKth(A, A_start + k / 2, B, B_start, k - k / 2)
else:
return self.findKth(A, A_start, B, B_start + k / 2, k - k / 2)
# @return a float
def findMedianSortedArrays(self, A, B):
n = len(A) + len(B)
if n % 2 == 0:
return (self.findKth(A, 0, B, 0, n / 2) + self.findKth(A, 0, B, 0, n / 2 + 1)) / 2.0
else:
return self.findKth(A, 0, B, 0, n / 2 + 1)```

``` int findMedian(int A[],int B[],int n,int low,int high) {
if (low > high) return NOT_FOUND;
else {
;
]) return A[n];
]) return A[k];
]) );
,high);
}
}
int twoArrayMedian(int X[],int Y[],int n) {
,n);
,n);
return median;
}  ```

## 010* Regular Expression Matching

Implement regular expression matching with support for `'.'` and `'*'`.

```'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true```
``` class Solution {
public:
bool isMatch(const char *s, const char *p) {
) ;
) != '*') {
&& (*p == *s || *p == , p + );
else return false;
}
else {
&& (*s == *p || *p == '.')) {
)) return true;
s++;
}
));
}
}
};```

## 011* Container With Most Water

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container.

``` class Solution:
# @return an integer
def maxArea(self, height):
n = len(height)
L = 0
R = n - 1
ans = 0
while L < R:
tmp = (R - L) * min(height[L], height[R])
if tmp > ans:
ans = tmp
if height[L] < height[R]:
b = height[L]
while L < n and height[L] <= b:
L += 1
else:
b = height[R]
while R >= 0 and height[R] <= b:
R -= 1
return ans```

## 012* Integer to Roman

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

``` class Solution:
# @return a string
def intToRoman(self, num):
s = ""
if num >= 1000:
i = num / 1000
for j in range(i):
s = s + "M"
num -= 1000 * i
if num >= 900:
s = s + "CM"
num -= 900
if num >= 500:
s = s + "D"
num -= 500
if num >= 400:
s = s + "CD"
num -= 400
if num >= 100:
i = num / 100
for j in range(i):
s = s + "C"
num -= 100 * i
if num >= 90:
s = s + "XC"
num -= 90
if num >= 50:
s = s + "L"
num -= 50
if num >= 40:
s = s + "XL"
num -= 40
if num >= 10:
i = num / 10
for j in range(i):
s = s + "X"
num -= 10 * i
if num >= 9:
s = s + "IX"
num -= 9
if num >= 5:
s = s + "V"
num -= 5
if num >= 4:
s = s + "IV"
num -= 4
for j in range(num):
s = s + "I"
return s```

## 013* Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

``` class Solution:
# @return an integer
def romanToInt(self, s):
n = len(s)
p = 0
num = 0
cnt = 0
while p < n:
if s[p] == 'M':
cnt = 0
while p < n and s[p] == 'M':
cnt += 1
p += 1
num += 1000 * cnt
elif p + 1 < n and s[p:p+2] == 'CM':
num += 900
p += 2
elif s[p] == 'D':
num += 500
p += 1
elif p + 1 < n and s[p:p+2] == 'CD':
num += 400
p += 2
elif s[p] == 'C':
cnt = 0
while p < n and s[p] == 'C':
cnt += 1
p += 1
num += 100 * cnt
elif p + 1 < n and s[p:p+2] == 'XC':
num += 90
p += 2
elif s[p] == 'L':
num += 50
p += 1
elif p + 1 < n and s[p:p+2] == 'XL':
num += 40
p += 2
elif s[p] == 'X':
cnt = 0
while p < n and s[p] == 'X':
cnt += 1
p += 1
num += 10 * cnt
elif p + 1 < n and s[p:p+2] == 'IX':
num += 9
p += 2
elif s[p] == 'V':
num += 5
p += 1
elif p + 1 < n and s[p:p+2] == 'IV':
num += 4
p += 2
elif s[p] == 'I':
cnt = 0
while p < n and s[p] == 'I':
cnt += 1
p += 1
num += cnt
return num```

## 016* 3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

```    For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).```
``` class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
sort(num.begin(), num.end());
int n = num.size();
int ans = 0x3f3f3f3f;
;
; p < n; p++) {
;
;
while (L < R) {
if (L == p) {
L++;
continue;
}
if (R == p) {
R--;
continue;
}
int sum = num[L] + num[R] + num[p];
if (abs(sum - target) < ans) {
ans = abs(sum - target);
res = sum;
}
if (sum < target) {
L++;
}
else if (sum > target) {
R--;
}
else {
ans = ;
res = sum;
break;
}
}
}
return res;
}
};```

python依然TLE，所以python有风险。。

## 017* 4Sum

Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

• Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
• The solution set must not contain duplicate quadruplets.
```    For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

A solution set is:
(-1,  0, 0, 1)
(-2, -1, 1, 2)
(-2,  0, 0, 2)```
``` class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
set<long long> st;
sort(num.begin(), num.end());
vector<vector<int> > res;
int n = num.size();
; i < n; i++){
; j < n; j++) {
;
;
while (L < R) {
int sum = num[i] + num[j] + num[L] + num[R];
if (sum < target) {
< R && num[L + ] == num[L]) L++;
L++;
}
else if (sum > target) {
&& num[R - ] == num[R]) R--;
R--;
}
else {
vector<int> v = { num[i], num[j], num[L], num[R] };
res.push_back(v);
< R && num[L + ] == num[L]) L++;
L++;
&& num[R - ] == num[R]) R--;
R--;
}
}
< n && num[j + ] == num[j]) j++;
}
< n && num[i + ] == num[i]) i++;
}
return res;
}
};```

## 018* Letter Combinations of a Phone Number

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

```Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
```

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

``` class Solution:
def gao(self, dep):
if dep == self.n:
s = ""
for c in self.s:
s+=c
self.ans.append(s)
return
idx = int(self.digits[dep])
for i in range(len(self.phone[idx])):
self.s.append(self.phone[idx][i])
self.gao(dep+1)
self.s.pop()
# @return a list of strings, [s1, s2]
def letterCombinations(self, digits):
self.phone = ["","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
self.ans = []
self.n = len(digits)
self.s = []
self.digits = digits
self.gao(0)
return self.ans```

## 021* Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

`"((()))", "(()())", "(())()", "()(())", "()()()"`

``` class Solution:
def gao(self, pl, pr):
if pl == self.n and pr == self.n:
gen = ""
for c in self.gen:
gen+=c
self.ans.append(gen)
return
if pl < self.n:
self.stack.append('(')
self.gen.append('(')
self.gao(pl + 1, pr)
self.gen.pop()
self.stack.pop()
if len(self.stack) > 0 and pr < self.n:
self.stack.pop()
self.gen.append(')')
self.gao(pl, pr + 1)
self.gen.pop()
self.stack.append('(')
# @param an integer
# @return a list of string
def generateParenthesis(self, n):
self.n = n
self.ans = []
self.stack = []
self.gen = []
self.gao(0, 0)
return self.ans```

## 023* Swap Nodes in Pairs

For example,
Given `1->2->3->4`, you should return the list as `2->1->4->3`.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

``` class Solution:
# @param a ListNode
# @return a ListNode
cur = tmp = pre = None
if cur != None and cur.next != None:
while cur != None:
if cur.next == None:
next = cur.next
if pre != None:
pre.next = next
tmp = next.next
next.next = cur
cur.next = tmp
pre = cur
cur = cur.next

## 024* Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: `1->2->3->4->5`

For k = 2, you should return: `2->1->4->3->5`

For k = 3, you should return: `3->2->1->4->5`

``` class Solution:
cnt = 0
while p != None:
p = p.next
cnt += 1
if cnt < k:
pre = p
next = None
tmp = None
while k > 1 and p.next != None:
tmp = next = p.next
p.next = next.next
next.next = pre
pre = tmp
k -= 1
# @param k, an integer
# @return a ListNode
while p != None:
lst = p
p = p.next
tmp, p = self.gao(p, k)
lst.next = tmp

## 029* Substring with Concatenation of All Words

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

For example, given:
S: `"barfoothefoobarman"`
L: `["foo", "bar"]`

You should return the indices: `[0,9]`.
(order does not matter).

``` class Solution:
def check(self, p):
#print "-------------------\n", p
L = R = p
cnt = 0
maxcnt = len(self.L)
while L + self.len <= len(self.S) and R + self.len <= len(self.S):
word = self.S[R:R+self.len]
#print L,R,cnt,word
if self.dict.has_key(word) == False:
L = R = R + self.len
cnt = 0
self.book = {}
continue
if self.book.has_key(word) == False:
self.book[word] = 0
self.book[word] += 1
cnt += 1
R += self.len
while self.book[word] > self.dict[word]:
pre = self.S[L:L+self.len]
self.book[pre] -= 1
cnt -= 1
L += self.len
if cnt == maxcnt:
self.ans.append(L)

# @param S, a string
# @param L, a list of string
# @return a list of integer
def findSubstring(self, S, L):
self.L = L
self.S = S
self.ans = []
self.dict = {}
self.len = len(L[0])
for c in L:
if self.dict.has_key(c) == False:
self.dict[c] = 0
self.dict[c] += 1
for i in xrange(self.len):
self.book = {}
self.check(i)
return self.ans```

## 033* Search in Rotated Sorted Array

Suppose a sorted array 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.

``` class Solution {
public:
int normalSearch(int A[], int L, int R, int target) {
while (L<=R) {
;
if (A[mid]==target) return mid;
;
;
}
;
}
int search(int A[], int n, int target) {
,R=n-;
while (L<=R) {
;
if (A[mid]==target) return mid;
if (L==mid) {
L+=;
continue;
}
if (R==mid) {
R-=;
continue;
}
if (A[mid]>A[L]) {
, target);
;
}
else {
, R, target);
;
}
}
;
}
};```

## 046* Permutations

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

``` class Solution {
private:
bool next(vector<int> &a, int n) {
||n==) return false;
;i>=;i--) {
]) {
;j>=;j--) {
if (a[j]>a[i]) {
swap(a[i],a[j]);
,R=n-;
while (L<R) {
swap(a[L],a[R]);
L++,R--;
}
return true;
}
}
}
}
return false;
}
public:
vector<vector<int> > permute(vector<int> &num) {
vector<vector<int> > ans;
sort(num.begin(),num.end());
ans.push_back(num);
while (next(num, num.size())) {
ans.push_back(num);
}
return ans;
}
};```

## 084* Largest Rectangle in Histogram

Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

The largest rectangle is shown in the shaded area, which has area = 10 unit.

For example,
Given height = [2,1,5,6,2,3],
return 10.

``` class Solution {
public:
int largestRectangleArea(vector<int> &h) {
int n = h.size();
vector<int> f(n), g(n);
;i<n;i++) {
f[i]=i;
g[i]=i;
}
;i<n;i++) {
>=  && h[f[i]-] >= h[i]) {
f[i]=f[f[i]-];
}
}
;i>=;i--) {
< n && h[g[i]+] >= h[i]) {
g[i]=g[g[i]+];
}
}
;
;i<n;i++) {
ans = max(ans, (g[i]-f[i]+)*h[i]);
}
return ans;
}
};```

## 091* Decode Ways

A message containing letters from `A-Z` is being encoded to numbers using the following mapping:

```'A' -> 1
'B' -> 2
...
'Z' -> 26
```

Given an encoded message containing digits, determine the total number of ways to decode it.

For example,
Given encoded message `"12"`, it could be decoded as `"AB"` (1 2) or `"L"` (12).

The number of ways decoding `"12"` is 2.

``` class Solution {
public:
int numDecodings(string s) {
int n = s.length();
) ;
vector<);
f[]=;
]==]=;
]=;
;i<=n;i++) {
]!=];
]==];
]==]>=]<=];
}
return f[n];
}
};```

## 092* Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given `1->2->3->4->5->NULL`m = 2 and n = 4,

return `1->4->3->2->5->NULL`.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

``` /**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
;i<m-;i++) {
pprev=pp;
pp=pp->next;
}
ListNode *prev=pp, *next=NULL, *p;
p=pp->next;
ListNode *last=pp;
for (int i=m;i<n;i++) {
next=p->next;
p->next = prev;
prev=p;
p=next;
}
last->next=p;
if (pprev) {
pprev->next=prev;
}
else {
}

}
};```

## 097* Interleaving String

Given s1s2s3, find whether s3 is formed by the interleaving of s1 and s2.

For example,
Given:
s1 = `"aabcc"`,
s2 = `"dbbca"`,

When s3 = `"aadbbcbcac"`, return true.
When s3 = `"aadbbbaccc"`, return false.

``` class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int n = s1.size();
int m = s2.size();
int len = s3.size();
&&m==) {
) return true;
else return false;
}
) {
if (s2==s3) return true;
else return false;
}
) {
if (s1==s3) return true;
else return false;
}
if (n+m!=len) return false;
vector<vector<bool> > f;
f.resize(n+);
;i<=n;i++) {
f[i].resize(m+);
}
f[][]=true;
;i<=n;i++) {
;j<=m;j++) {
&& s1[i-]==s3[i+j-] && f[i-][j]) f[i][j]=true;
&& s2[j-]==s3[i+j-] && f[i][j-]) f[i][j]=true;
}
}
if (f[n][m]) return true;
return false;
}
};```

## 099* Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?

confused what `"{1,#,2,3}"` means? > read more on how binary tree is serialized on OJ.

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

```   1
/ \
2   3
/
4
\
5
```

The above binary tree is serialized as `"{1,2,3,#,#,4,#,#,5}"`.

``` /**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
TreeNode *mis1, *mis2, *pre;
public:
void dfs(TreeNode *root) {
if (root->left != NULL) dfs(root->left);
if (pre!=NULL && root->val < pre->val) {
if (mis1 == NULL) {
mis1 = pre;
mis2 = root;
}
else {
mis2 = root;
}
}
pre = root;
if (root->right != NULL) dfs(root->right);
}
void recoverTree(TreeNode *root) {
if (root == NULL) return;
mis1 = mis2 = pre = NULL;
dfs(root);
if (mis1!=NULL && mis2!=NULL) {
int tmp = mis1->val;
mis1->val = mis2->val;
mis2->val = tmp;
}
}
};```

## LeetCode里有特色的问题存档的更多相关文章

1. LeetCode(5) － Longest Palindromic Substring

2. 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)

转自  http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...

3. Leetcode - Letter Combination Of A Phone Number

Given a digit string, return all possible letter combinations that the number could represent. A map ...

4. ZigZag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

5. 转：NLog之：文件类型目标（File target）

转:http://www.cnblogs.com/RitchieChen/archive/2012/07/16/2594308.html 英文原文[http://nlog-project.org/wi ...

6. [CareerCup] 11.2 Sort Anagrams Array 异位词数组排序

11.2 Write a method to sort an array of strings so that all the anagrams are next to each other. 这道题 ...

7. Careercup - Google面试题 - 4877486110277632

2014-05-08 05:16 题目链接 原题: Given a circle with N defined points and a point M outside the circle, fin ...

8. NLP | 自然语言处理 - 标注问题与隐马尔科夫模型（Tagging Problems, and Hidden Markov Models）

什么是标注? 在自然语言处理中有一个常见的任务,即标注.常见的有:1)词性标注(Part-Of-Speech Tagging),将句子中的每一个词标注词性,比如名词.动词等:2)实体标注(Name E ...

9. NLP | 自然语言处理 - 解析（Parsing, and Context-Free Grammars）

什么是解析? 在自然语言的学习过程,个人一定都学过语法,比如句子能够用主语.谓语.宾语来表示.在自然语言的处理过程中.有很多应用场景都须要考虑句子的语法,因此研究语法解析变得很重要. 语法解析有两个基 ...

## 随机推荐

1. ASP.NET MVC5+EF6+EasyUI 后台管理系统（41）-组织架构

系列目录 本节开始我们要实现工作流,此工作流可以和之前的所有章节脱离关系,也可以紧密合并. 我们当初设计的项目解决方案就是可伸缩可以拆离,可共享的项目解决方案.所以我们同时要添加App.Flow文件夹 ...

2. 在JaveWeb项目中配置Spring 匿名访问时，匹配规则的变相实现/*

实现/* /** * 根据当前的URL返回该url的角色集合. * 1.如果当前的URL在匿名访问的URL集合当中时,在当前的角色中添加匿名访问的角色(SysRole.ROLE_CONFIG_ANON ...

3. HDU5887 Herbs Gathering(2016青岛网络赛 搜索 剪枝)

背包问题,由于数据大不容易dp,改为剪枝,先按性价比排序,若剩下的背包空间都以最高性价比选时不会比已找到的最优解更好时则剪枝,即 if(val + (LD)pk[d].val / (LD)pk[d]. ...

4. Dump中查看dictionary信息的方法

In order to dump the contents of a dictionary, you need to start with either the MethodTable or the ...

5. jQuery 跨域访问的三种方式 No &#39;Access-Control-Allow-Origin&#39; header is present on the reque

6. CFNetwork的错误代码参考

所有的错误代码是在对“CFNetwork的错误代码参考” 小提取CFURL和CFURLConnection错误: kCFURLErrorUnknown = -998, kCFURLErrorCance ...

7. linux /boot 清理

随着升级 /boot分区会越来越满 导致后续无法升级  原因是因为每次升级有可能升级内核  但是旧的内核没有删除  所以导致/boot一直增大 解决办法就是删除不需要的内核,一下步骤: 查看所有安装的 ...

8. netty学习

1.不选择java原生nio的原因   (1)nio的类库和api繁杂   (2)需要具备其他的额外的技能做铺垫,例如熟悉java多线程编程.   (3)可靠性能力补齐的工作量和难度都非常大,例如客户 ...

9. Sqli-LABS通关笔录-9[延时注入]

通过这个关卡 1.更快的掌握到了如何判断是否是延时注入 无论咋输入,都不行.当payload为: http://127.0.0.1/sql/Less-9/index.php?id=1' and sle ...

10. 奇葩问题之ToolBar返回键失效

今天遇到一个奇葩问题,先说现象:接口调用成功,但是在后台业务上报错时(比如:手机号已经被注册过时,接口调用成功,但是后台返回了错误信息:手机号已被注册),toolBar的返回键失效了. 后来仔细看了一 ...