LeetCode(Easy)--C++笔记

时间:2021-04-13 15:37:52

前言:这是关于LeetCode上面练习题C++的笔记,有些地方参考有网友的解题方法(可能有些参考没能注明,望谅解),如有需要改进的地方希望留言指教,多谢!

目录:

  1. ZigZag Conversion
  2. Reverse digits of an integer
  3. Implement atoi to convert a string to an integer
  4. Determine whether an integer is a palindrome
  5. Write a function to find the longest common prefix string amongst an array of strings
  6. Remove Nth Node From End of List
  7. Valid Parentheses
  8. Merge Two Sorted Lists
  9. Remove Duplicates from Sorted Array
  10. Remove Element
  11. Valid Sudoku
  12. Length of Last Word
  13. Add Binary
  14. Climbing Stairs
  15. Remove Duplicates from Sorted List
  16. Merge Sorted Array
  17. Same Tree
  18. Symmetric Tree
  19. Binary Tree Level Order Traversal
  20. Maximum Depth of Binary Tree
  21. Binary Tree Level Order Traversal II
  22. Balanced Binary Tree
  23. Minimum Depth of Binary Tree
  24. Path Sum
  25. Pascal's Triangle
  26. Pascal's Triangle II
  27. Valid Palindrome
  28. Find Minimum in Rotated Sorted Array
  29. Min Stack
  30. Intersection of Two Linked Lists
  31. Compare Version Numbers
  32. Excel Sheet Column Title
  33. Factorial Trailing Zeroes
  34. Rotate Array
  35. Reverse Bits
  36. Number of 1 Bits

1.ZigZag Conversion 返回目录

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y I R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

这问题原理参考:http://www.cnblogs.com/sanghai/p/3632528.html

class Solution {
public:
string convert(string s, int nRows)
{
if(nRows == 1) return s;
string res[nRows];
int i = 0, j, gap = nRows-2;
while(i < s.size())
{
for(j = 0; i < s.size() && j < nRows; ++j) res[j] += s[i++];
for(j = gap; i < s.size() && j > 0; --j) res[j] += s[i++];
}
string str = "";
for(i = 0; i < nRows; ++i)
str += res[i]; // 逐行合并
return str;
}
};

2. Reverse digits of an integer.返回目录

Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Update (2014-11-10):
Test cases had been added to test the overflow behavior.

 1 class Solution {
2 public:
3 int reverse(int x)
4 {
5 if (x >= INT_MAX || x <= INT_MIN) //如果溢出
6 {
7 return 0;
8 }
9
10 /*数据反转*/
11 int abs_x = abs(x);
12 double res = 0;
13 bool overflow = false; // 溢出标志
14 while (abs_x)
15 {
16 res = res * 10 + abs_x % 10;
17 /*在反转过程中,每计算一次,就去判断是否溢出,如果溢出则立即将溢出标志置为true,中断循环*/
18 if ((x > 0 && res > INT_MAX) || (x < 0 && -res < INT_MIN) )
19 {
20 overflow = true;
21 break;
22 }
23 abs_x /= 10;
24 }
25
26 if (overflow)
27 return 0;
28 else
29 {
30 res = (int)res;
31 return x > 0 ? res : (0 - res);
32 }
33
34 }
35 };

3.Implement atoi to convert a string to an integer.返回目录

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

class Solution {
public:
int atoi(string str) {
int in;
stringstream s(str); // 将字符串字符串流关联
s >> in; // 将字符串流输入给数字
return in;
}
};

4.Determine whether an integer is a palindrome.返回目录

Do this without extra space.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

 1 class Solution {
2 public:
3 bool isPalindrome(int x)
4 {
5 if(x < 0)
6 return false;
7 /*将数转换为字符串*/
8 string str;
9 stringstream s;
10 s << x;
11 str = s.str();
12 /*正向和逆向同时遍历字符串,并比较*/
13 string::iterator beg = str.begin();
14 string::reverse_iterator rbeg = str.rbegin();
15 while(beg != str.end())
16 {
17 if (*beg != *rbeg)
18 return false;
19 ++beg;
20 ++rbeg;
21 }
22 return true;
23 }
24 };

5.Write a function to find the longest common prefix string amongst an array of strings.返回目录

 1 class Solution {
2 public:
3 string longestCommonPrefix(vector<string> &strs)
4 {
5 string common = "";
6 if (strs.size() == 0) return common;
7 vector<string>::size_type len = strs[0].size();
8
9 /*最长共同前缀不会超过数组中最短的字符串长度,所以先找出最短字符串长度,即共同前缀长度的上限*/
10 for (vector<string>::size_type i = 1; i < strs.size(); ++i)
11 {
12 if (strs[i].size() < len)
13 len = strs[i].size();
14 }
15
16 /*逐个字符比较*/
17 bool flag = true;
18 for (vector<string>::size_type i = 0; i < len; ++i)
19 {
20 char ch = strs[0][i];
21 for (vector<string>::size_type j = 1; j < strs.size(); ++j)
22 {
23 if (ch != strs[j][i])
24 {
25 flag = false;
26 break;
27 }
28 }
29 if (flag)
30 common.push_back(ch);
31 else
32 break;
33 }
34 return common;
35 }
36 };

6.Remove Nth Node From End of List 返回目录

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

 class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n){
if (head == NULL || head->next == NULL) return NULL; ListNode *first = head;
ListNode *second = head; for (int i = ; i < n; i++) first = first->next; if (first == NULL) return head->next;
while(first->next != NULL){
first = first->next;
second = second->next; // 此时second指向倒数n-1位置的结点
} second->next = second->next->next; return head;
};

7.Valid Parentheses 返回目录

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

 1 class Solution {
2 public:
3 bool isValid(string s)
4 {
5 /*典型地用栈进行括号匹配的问题*/
6 stack<char> st;
7 string::size_type len = s.size();
8 for (string::size_type i = 0; i < len; ++i)
9 {
10 char ch = s.at(i);
11 char ch_pop;
12 if (ch == '{' || ch == '[' || ch == '(')
13 st.push(ch);
14 else
15 {
16 if (st.empty()) return false;
17 else
18 {
19 ch_pop = st.top();
20 if (ch_pop == '(' && ch != ')') return false;
21 else if (ch_pop == '{' && ch != '}') return false;
22 else if (ch_pop == '[' && ch != ']') return false;
23 else st.pop();
24 }
25 }
26
27 }
28 if (st.empty()) return true;
29 else return false;
30 }
31 };

8. Merge Two Sorted Lists 返回目录

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

 1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
12 {
13 if (l1 == NULL)
14 return l2;
15 if (l2 == NULL)
16 return l1;
17 ListNode *head;
18 if(l1 -> val <= l2 -> val)
19 {
20 head = l1;
21 head -> next = mergeTwoLists(l1 -> next, l2);
22 }
23 else
24 {
25 head = l2;
26 head -> next = mergeTwoLists(l1, l2 -> next);
27 }
28 return head;
29 }
30 };

9.Remove Duplicates from Sorted Array 返回目录

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

 1 class Solution {
2 public:
3 int removeDuplicates(int A[], int n)
4 {
5 if (n == 0)
6 return 0;
7 int count = 1;
8 for (size_t i = 1; i < n; ++i)
9 {
10 if (A[i] != A[i - 1])
11 {
12 A[count++] = A[i];
13 }
14 }
15 return count;
16 }
17 };

10. Remove Element 返回目录

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

class Solution {
public:
int removeElement(int A[], int n, int elem)
{ int count = 0;
for (int i = 0; i < n; ++i)
{
if (A[i] != elem) A[count++] = A[i];
}
return count;
}
};

11.Valid Sudoku 返回目录

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

LeetCode(Easy)--C++笔记

A partially filled sudoku which is valid.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

class Solution {
public:
vector<vector<char> > transport(vector<vector<char> > m)
{ vector<vector<char> > ret(9, vector<char>(9, '0'));
for (unsigned i = 0; i < 9; ++i)
for (unsigned j = 0; j < 9; ++j)
ret[j][i] = m[i][j];
return ret;
} bool isValidRow(vector<char> row)
{
map<char, int> counter;
vector<char>::iterator beg = row.begin();
while (beg != row.end())
{
++counter[*beg];
if (*beg != '.' && counter[*beg] > 1) return false;
else ++beg;
}
return true;
} bool isValidSudoku(vector<vector<char> > &board)
{
vector<vector<char> > transMatrix = transport(board);
vector<char> v0,v1,v2;
for (unsigned i = 0; i < 9; ++i)
{
if (!(isValidRow(board[i]) && isValidRow(transMatrix[i])))
return false;
if (v0.size() < 9)
{
v0.push_back(board[i][0]);
v0.push_back(board[i][1]);
v0.push_back(board[i][2]);
v1.push_back(board[i][3]);
v1.push_back(board[i][4]);
v1.push_back(board[i][5]);
v2.push_back(board[i][6]);
v2.push_back(board[i][7]);
v2.push_back(board[i][8]);
}
bool flag = (i == 2 || i == 5 || i == 8);
if ( flag && isValidRow(v0) && isValidRow(v1) && isValidRow(v2))
{
v0.clear();
v1.clear();
v2.clear();
}
else if(flag)
{
return false;
}
}
return true;
}
};

12.Length of Last Word 返回目录

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

For example, 
Given s = "Hello World",
return 5.

class Solution {
public:
int lengthOfLastWord(const char *s)
{
int len=strlen(s);
int sum=0;
while(s[len-1]==' ') len--;
for(int i=len-1;i>=0;i--)
{
if(s[i]!=' ') sum++;
else break;
}
return sum;
}
};

13.Add Binary 返回目录

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

 1 class Solution {
2 public:
3 string addBinary(string a, string b)
4 {
5 unsigned sz = a.size() >= b.size() ? a.size() : b.size();
6 reverse(a);
7 reverse(b);
8 int sum;
9 int tmp = 0;
10 string ret;
11 for (unsigned i = 0; i < sz; ++i)
12 {
13
14 int A = i >= a.size() ? 0 : a.at(i) - '0';
15 int B = i >= b.size() ? 0 : b.at(i) - '0';
16 sum = (A + B + tmp) % 2;
17 ret += sum + '0';
18 tmp = (A + B + tmp) / 2;
19 }
20 if (tmp) ret += tmp + '0';
21 reverse(ret);
22 return ret;
23 }
24 void reverse(string &s)
25 {
26 string ret;
27 string::reverse_iterator rbeg = s.rbegin();
28 while (rbeg != s.rend())
29 ret += *rbeg++;
30 s = ret;
31 }
32
33 };

14.Climbing Stairs 返回目录

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

 1 class Solution {
2 public:
3 int climbStairs(int n)
4 {
5
6 /* 利用DP的方法,一个台阶的方法次数为1次,两个台阶的方法次数为2个。
7 n个台阶的方法可以理解成上n-2个台阶,然后2步直接上最后一步;或者上n-1个台阶,再单独上一步。
8 公式是S[n] = S[n-1] + S[n-2] S[1] = 1 S[2] = 2
9 */
10 if (n <= 2) return n;
11 else
12 {
13 int* step = new int[n];
14 step[0] = 1;
15 step[1] = 2;
16 for(int i = 2; i < n; i++)
17 {
18 step[i] = step[i-1] + step[i-2];
19 }
20 return step[n - 1];
21 }
22
23 }
24 };

15.Remove Duplicates from Sorted List 返回目录

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

 1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 ListNode *deleteDuplicates(ListNode *head)
12 {
13 if (head == NULL || head -> next == NULL) return head;
14 ListNode *cur = head;
15 ListNode *ret = new ListNode(head -> val);
16 ListNode *newHead = ret;
17 while(cur != NULL)
18 {
19 if (cur -> val != newHead -> val)
20 {
21 newHead -> next = new ListNode(cur -> val);
22 newHead = newHead -> next;
23 }
24 cur = cur -> next;
25 }
26 return ret;
27 }
28 };

16.Merge Sorted Array 返回目录

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m andn respectively.

class Solution {
public:
void merge(int A[], int m, int B[], int n)
{
/*注意到两个数组本来是有序的*/
if(n == 0) return;
int k = m + n -1;
int i = m - 1;
int j = n - 1;
while(i >= 0 && j >= 0)
{
A[k--] = A[i] > B[j] ? A[i--] : B[j--];
}
while (j >= 0)
A[k--] = B[j--];
}
};

17.Same Tree 返回目录

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

 1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 bool isSameTree(TreeNode *p, TreeNode *q)
13 {
14 if(p == NULL && q == NULL)
15 return true;
16 if(p == NULL || q == NULL)
17 return false;
18 if (p -> val != q -> val)
19 return false;
20 return isSameTree(p -> left, q -> left) && isSameTree(p -> right, q -> right);
21 }
22 };

18.Symmetric Tree 返回目录

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
/ \
2 2
/ \ / \
3 4 4 3

But the following is not:

    1
/ \
2 2
\ \
3 3

Note:
Bonus points if you could solve it both recursively and iteratively.

 1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 bool isSymmetric(TreeNode *root)
13 {
14 if (root == NULL)
15 return true;
16 return isMirror(root -> left, root -> right);
17 }
18 bool isMirror(TreeNode *t1, TreeNode *t2)
19 {
20 if (t1 == NULL && t2 == NULL)
21 return true;
22 if (t1 == NULL || t2 == NULL)
23 return false;
24 if (t1 -> val != t2 -> val)
25 return false;
26 return isMirror(t1 -> left, t2 -> right) && isMirror(t1 -> right, t2 -> left);
27 }
28 };

19.Binary Tree Level Order Traversal 返回目录

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
/ \
9 20
/ \
15 7

return its level order traversal as:

[
[3],
[9,20],
[15,7]
]
 1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 vector<vector<int> > levelOrder(TreeNode *root)
13 {
14 vector<vector<int> > ret;
15 if (root == NULL) return ret;
16 /* 利用队列先进先出的特点,每次遍历至某一个结点时,将其孩子结点(如果存在)
17 压入队列,所以先访问的结点的孩子结点 也会先于 后访问的结点的孩子结点 被
18 访问
19 */
20 vector<int> tmp;
21 queue<TreeNode *> q;
22 q.push(root);
23 int count = 1;
24 while (!q.empty())
25 {
26 tmp.clear();
27 int newCount = 0;//记录每一层的结点数
28 for (int i = 0; i < count; ++i)
29 {
30 root = q.front();
31 q.pop();
32 tmp.push_back(root -> val);
33 // 访问一个结点,就将其孩子结点入队列作为下一层结点被访问
34 if (root -> left != NULL)
35 {
36 q.push(root -> left);
37 ++newCount;
38 }
39 if (root -> right != NULL)
40 {
41 q.push(root -> right);
42 ++newCount;
43 }
44 }
45 count = newCount;
46 ret.push_back(tmp);
47 }
48 }
49 };

20.Maximum Depth of Binary Tree 返回目录

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root)
{
if (root == NULL) return 0;
//if (root -> left == NULL && root -> right == NULL) return 1;
int lmd = maxDepth(root -> left);
int rmd = maxDepth(root -> right);
return (lmd >= rmd ? lmd : rmd) + 1;
}
};

21.Binary Tree Level Order Traversal II  返回目录

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
/ \
9 20
/ \
15 7

return its bottom-up level order traversal as:

[
[15,7],
[9,20],
[3]
]
 1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 vector<vector<int> > levelOrderBottom(TreeNode *root)
13 {
14 // 首先从上至下层次遍历
15 vector<vector<int> > ret1;
16 if (root == NULL) return ret1;
17 queue<TreeNode*> q;
18 q.push(root);
19 int count = 1;
20 vector<int> a;
21 while(!q.empty())
22 {
23 a.clear();
24 int newCount = 0;
25 for (int i = 0; i < count; ++i)
26 {
27 TreeNode* tmp = q.front();
28 q.pop();
29 a.push_back(tmp -> val);
30 if (tmp -> left != NULL)
31 {
32 q.push(tmp -> left);
33 ++newCount;
34 }
35 if (tmp -> right != NULL)
36 {
37 q.push(tmp -> right);
38 ++newCount;
39 }
40 }
41 count = newCount;
42 ret1.push_back(a);
43 }
44 // 将上面遍历的结果反转
45 vector<vector<int> > ret2;
46 vector<vector<int> >::reverse_iterator rbeg = ret1.rbegin();
47 while(rbeg != ret1.rend())
48 {
49 ret2.push_back(*rbeg++);
50 }
51 return ret2;
52 }
53 };

22.Balanced Binary Tree  返回目录

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

 1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 bool isBalanced(TreeNode *root)
13 {
14 if (root == NULL)
15 return true;
16 int ld = treeDepth(root -> left);
17 int rd = treeDepth(root -> right);
18 if (abs(ld - rd) <= 1) return isBalanced(root -> left) && isBalanced(root -> right);
19 else return false;
20
21
22 }
23
24 // 递归算出树的深度
25 int treeDepth(TreeNode *root)
26 {
27 if (root == NULL) return 0;
28 if (root -> left == NULL && root -> right == NULL) return 1;
29 int ld = treeDepth(root -> left);
30 int rd = treeDepth(root -> right);
31 return ld >= rd ? ld + 1 : rd + 1;
32 }
33 };

23.Minimum Depth of Binary Tree 返回目录

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

 1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 int minDepth(TreeNode *root)
13 {
14 if (root == NULL)
15 return 0;
16 int ld = minDepth(root -> left);
17 int rd = minDepth(root -> right);
18 if (ld == 0 && rd == 0)
19 return 1;
20
21 // 这个条件如果成立表明只有右子树,于是左子树的深度
22 // 设为无穷大,这样的话,在比较的时候就会保证返回右子树
23 // 深度
24 if (ld == 0)
25 ld = INT_MAX;
26 // 原理同上
27 if (rd == 0)
28 rd = INT_MAX;
29
30 return ld >= rd ? (rd + 1) : (ld + 1);
31 }
32 };

24.Path Sum  返回目录

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

 1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 bool hasPathSum(TreeNode *root, int sum)
13 {
14 if (root == NULL)
15 return false;
16 else if (root -> left == NULL && root -> right == NULL && sum == root -> val)
17 return true;
18 else
19 return hasPathSum(root -> left, sum - (root -> val)) || hasPathSum(root -> right, sum - (root -> val));
20
21 }
22 };

25.Pascal's Triangle 返回目录

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
class Solution {
public:
vector<vector<int> > generate(int numRows)
{
vector<vector<int> > result(numRows, vector<int>());
if (numRows == 0)
return result;
// 每一行的最左边必定是1
result[0].push_back(1);
for (int i = 1; i < numRows; ++i)
{
result[i].push_back(1);
for (int j = 1; j < i; ++j)
{
result[i].push_back(result[i - 1][j - 1] + result[i - 1][j]);
}
// 每一行的最右边必定是1
result[i].push_back(1);
}
return result;
}
};

26.Pascal's Triangle II  返回目录

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?

class Solution {
public:
vector<int> getRow(int rowIndex)
{
vector<int> result(rowIndex+2,0);
result[1]=1;
for(int i=0;i<rowIndex;i++)
{
for(int j=rowIndex+1;j>0;j--)
{
result[j]= result[j-1]+result[j];
}
}
result.erase(result.begin());
return result;
}
};

27.Valid Palindrome  返回目录

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

 1 class Solution {
2 public:
3 bool isPalindrome(string s)
4 {
5 if (s.size() <= 1)
6 return true;
7
8 string str;
9 string::iterator it = s.begin();
10 while (it != s.end())
11 {
12
13 if (isalnum(*it))
14 str.push_back(*it);
15
16 ++it;
17 }
18
19 if(str.empty())
20 return true;
21 string::iterator beg = str.begin();
22 string::reverse_iterator rbeg = str.rbegin();
23 while (beg != str.end())
24 {
25 if (tolower(*beg) != tolower(*rbeg))
26 {
27 return false;
28 }
29 ++beg;
30 ++rbeg;
31 }
32 return true;
33 }
34 bool isalnum(char ch)
35 {
36 if ((ch >='0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') )
37 return true;
38 else
39 return false;
40 }
41 char tolower(char ch)
42 {
43 if (ch >= 'A' && ch <= 'Z')
44 return ch + 32;
45 else
46 return ch;
47 }
48
49 };

28.Find Minimum 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).

Find the minimum element.

You may assume no duplicate exists in the array.

 1 class Solution {
2 public:
3 int findMin(vector<int> &num)
4 {
5 /*最小数字的特点是:左右两边的数字都比该数字大*/
6 typedef vector<int>::size_type st;
7 st sz = num.size();
8 st left = 0;
9 st right = 0;
10 for (st i = 0; i < sz; ++i)
11 {
12 if (i == 0)
13 left = sz - 1;
14 else
15 left = i - 1;
16 if (i == sz - 1)
17 right = 0;
18 else
19 right = i + 1;
20 if (num[left] >= num[i] && num[right] >= num[i])
21 return num[i];
22 }
23 }
24 };

29.Min Stack  返回目录

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.
 1 class MinStack {
2 public:
3 void push(int x)
4 {
5 ++topid;
6 mystack.push_back(x);
7 if (topid == 0 || x < min)
8 min = x;
9 }
10
11 void pop()
12 {
13 int p = *(mystack.end() - 1);
14 if (topid != -1)
15 {
16 mystack.erase(mystack.end() - 1);
17 --topid;
18 }
19 if (p == min)
20 {
21 min = mystack[0];
22 for (unsigned id = 0; id < mystack.size(); ++id)
23 {
24 if (mystack[id] < min)
25 min = mystack[id];
26 }
27 }
28 }
29
30 int top() {
31 if (topid != -1)
32 return mystack[topid];
33 else
34 return 0;
35 }
36
37 int getMin()
38 {
39 return min;
40 }
41 private:
42 vector<int> mystack;
43 int topid = -1;
44 int min;
45
46 };

30.Intersection of Two Linked Lists  返回目录

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A:          a1 → a2

c1 → c2 → c3

B: b1 → b2 → b3

begin to intersect at node c1.

Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.
 1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
12 {
13 if (headA == NULL || headB == NULL) // 如果有一个为NULL,就返回NULL
14 return NULL;
15
16 /*计算出两个链表的长度*/
17 ListNode *rearA = headA;
18 int lenA = 0;
19 ListNode *rearB = headB;
20 int lenB = 0;
21
22 while(rearA -> next != NULL)
23 {
24 rearA = rearA -> next;
25 ++lenA;
26 }
27 while(rearB -> next != NULL)
28 {
29 rearB = rearB -> next;
30 ++lenB;
31 }
32
33 //如果两个链表最后一个元素还不相同,就证明没有交集
34 if(rearA != rearB)
35 return NULL;
36 // 否则的话证明 有交集,注意到交集之后的部分完全相同
37 // 让较长的结点先前进几步,与短链表保持一致
38 else
39 {
40 int dis = lenA - lenB;
41 ListNode *p = headA;
42 ListNode *q = headB;
43 if (dis >= 0)
44 {
45 while(dis--) p = p -> next;
46 while(p != q)
47 {
48 p = p -> next;
49 q = q -> next;
50 }
51 return p;
52 }
53 else
54 {
55 dis = abs(dis);
56 while(dis--) q = q -> next;
57 while(p != q)
58 {
59 p = p -> next;
60 q = q -> next;
61 }
62 return p;
63 }
64 }
65
66 }
67 };

31.Compare Version Numbers  返回目录

Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.

You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.

Here is an example of version numbers ordering:

0.1 < 1.1 < 1.2 < 13.37
 1 class Solution {
2 public:
3 int compareVersion(string version1, string version2)
4 {
5 unsigned start1 = 0;
6 unsigned start2 = 0;
7 unsigned end1 = 0;
8 unsigned end2 = 0;
9 int ret = 0;
10 while (end1 < version1.length() || end2 < version2.length())
11 {
12 while (end1 < version1.length() && version1.at(end1) != '.') ++end1;
13 while (end2 < version2.length() && version2.at(end2) != '.') ++end2;
14 int ret1, ret2;
15
16 if (end1 > version1.length())
17 ret1 = 0;
18 else
19 {
20 string substr1 = version1.substr(start1, end1);
21 stringstream s1(substr1);
22 s1 >> ret1;
23 }
24 if (end2 > version2.length())
25 ret2 = 0;
26 else
27 {
28 string substr2 = version2.substr(start2, end2);
29 stringstream s2(substr2);
30 s2 >> ret2;
31 }
32 ret = ret1 - ret2;
33 if (ret != 0)
34 {
35 return ret > 0 ? 1 : -1;
36 }
37 start1 = ++end1;
38 start2 = ++end2;
39 }
40 return ret;
41 }
42 };

32.Excel Sheet Column Title  返回目录

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

    1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
 1 class Solution {
2 public:
3 string convertToTitle(int n)
4 {
5 //本质上是10进制向26进制转换
6 if(n < 1)
7 return "";
8 else
9 {
10 string result = "";
11 while(n)
12 {//get every letter in n from right to left
13 n --;
14 char c = n%26 + 'A';
15 result += c;
16 n /= 26;
17 }
18 reverse(result.begin(), result.end());
19 return result;
20 }
21 }
22 };

33.Factorial Trailing Zeroes  返回目录

Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.

class Solution {
public:
int trailingZeroes(int n) {
int ret = 0;
while(n)
{
ret += n / 5;
n /= 5;
}
return ret;
}
};

34.Rotate Array  返回目录

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

class Solution {
public:
void rotate(int nums[], int n, int k)
{
int *newNums = new int[n];
for (int i = 0; i < n; ++i)
{
newNums[i] = nums[i];
}
for (int i = 0; i < n; ++i)
{
if (k % n + i < n)
nums[i + k % n] = newNums[i];
else
nums[i + k % n - n] = newNums[i];
}
}
};

35.Reverse Bits  返回目录

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).

 1 class Solution {
2 public:
3 uint32_t reverseBits(uint32_t n)
4 {
5 int bin[32] = {0};
6 dec2binary(n, bin);
7 int rbin[32] = {0};
8 for (size_t i = 32, k = 0; i > 0; --i,++k)
9 {
10 rbin[k] = bin[i - 1];
11 }
12
13 return binary2dec(rbin);
14 }
15 private:
16 void dec2binary(uint32_t n, int ret[])
17 {
18 unsigned i = 0;
19 while (n)
20 {
21 ret[i++] = n % 2;
22 n /= 2;
23 }
24 }
25 uint32_t binary2dec(int buff[])
26 {
27 uint32_t ret = 0;
28
29 for (size_t i = 0; i < 32; ++i)
30 {
31 ret += buff[i] * pow(2, i);
32 }
33 return ret;
34 }
35
36 };

36.Number of 1 Bits  返回目录

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as theHamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

class Solution {
public:
int hammingWeight(uint32_t n)
{
int count = 0;
while (n != 0)
{
count += n & 0x01;
n = n >> 1;
}
return count;
}
};