- 二維數(shù)組中的查找
在一個(gè)二維數(shù)組中(每個(gè)一維數(shù)組的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個(gè)函數(shù),輸入這樣的一個(gè)二維數(shù)組和一個(gè)整數(shù),判斷數(shù)組中是否含有該整數(shù)。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool Find(int target, vector<vector<int>> array) {
int m = array.size(), n = array[0].size();
int row = 0, col = n - 1;
while (row <= m - 1 && col >= 0) {
if (array[row][col] == target) {
return true;
} else if (array[row][col] < target) {
row++;
} else {
col--;
}
}
return false;
}
};
- 從尾到頭打印鏈表
輸入一個(gè)鏈表,按鏈表值從尾到頭的順序返回一個(gè)ArrayList。
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
vector<int> printListFromTailToHead(ListNode *head) {
vector<int> res;
auto cur = head;
while (cur) {
res.push_back(cur->val);
cur = cur->next;
}
reverse(res.begin(), res.end());
return res;
}
};
- 重建二叉樹
輸入某二叉樹的前序遍歷和中序遍歷的結(jié)果,請重建出該二叉樹。假設(shè)輸入的前序遍歷和中序遍歷的結(jié)果中都不含重復(fù)的數(shù)字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹并返回。
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode *reConstructBinaryTree(vector<int> pre, vector<int> vin) {
return helper(pre, vin, 0, 0, pre.size());
}
TreeNode *helper(vector<int> &pre, vector<int> &vin, int preStart,
int inStart, int length) {
if (length == 0) {
return NULL;
}
TreeNode *root = new TreeNode(pre[preStart]);
if (length == 1) {
return root;
}
int pos = find(vin.begin() + inStart, vin.begin() + inStart + length,
pre[preStart]) -
vin.begin();
root->left = helper(pre, vin, preStart + 1, inStart, pos - inStart);
root->right = helper(pre, vin, preStart + (pos - inStart) + 1, pos + 1,
(length - 1 - (pos - inStart)));
return root;
}
};
- 用兩個(gè)棧實(shí)現(xiàn)隊(duì)列
用兩個(gè)棧來實(shí)現(xiàn)一個(gè)隊(duì)列,完成隊(duì)列的Push和Pop操作。 隊(duì)列中的元素為int類型。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void push(int node) { stack1.push(node); }
int pop() {
if (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.top());
stack1.pop();
}
}
auto res = stack2.top();
stack2.pop();
return res;
}
private:
stack<int> stack1;
stack<int> stack2;
};
- 旋轉(zhuǎn)數(shù)組的最小數(shù)字
把一個(gè)數(shù)組最開始的若干個(gè)元素搬到數(shù)組的末尾,我們稱之為數(shù)組的旋轉(zhuǎn)。 輸入一個(gè)非減排序的數(shù)組的一個(gè)旋轉(zhuǎn),輸出旋轉(zhuǎn)數(shù)組的最小元素。 例如數(shù)組{3,4,5,1,2}為{1,2,3,4,5}的一個(gè)旋轉(zhuǎn),該數(shù)組的最小值為1。 NOTE:給出的所有元素都大于0,若數(shù)組大小為0,請返回0。
#include <bits/stdc++.h>
using namespace std;
// lc153 154題
// 有重復(fù)元素的寫法
class Solution {
public:
int minNumberInRotateArray(vector<int> rotateArray) {
int m = rotateArray.size(), left = 0, right = m - 1;
while (left < right) {
int mid = (left + right) / 2;
if (rotateArray[mid] < rotateArray[right]) {
right = mid;
} else if (rotateArray[mid] > rotateArray[right]) {
left = mid + 1;
} else {
right--;
}
}
return rotateArray[left];
}
};
// 這是沒有重復(fù)元素的做法
class Solution_1 {
public:
int minNumberInRotateArray(vector<int> rotateArray) {
int left = 0, right = rotateArray.size() - 1;
while (left < right) {
int mid = (left + right) / 2;
if (rotateArray[mid] < rotateArray[right]) {
right = mid;
} else {
left = mid + 1;
}
}
return rotateArray[left];
}
};
- 變態(tài)跳臺階
一只青蛙一次可以跳上1級臺階,也可以跳上2級……它也可以跳上n級。求該青蛙跳上一個(gè)n級的臺階總共有多少種跳法。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int jumpFloorII(int number) { return 1 << (--number); }
};
- 矩形覆蓋
我們可以用21的小矩形橫著或者豎著去覆蓋更大的矩形。請問用n個(gè)21的小矩形無重疊地覆蓋一個(gè)2*n的大矩形,總共有多少種方法?
class Solution {
public:
int rectCover(int number) {
if (number == 0 || number == 1) {
return number;
}
int prev = 1, cur = 1;
for (int i = 2; i <= number; i++) {
int temp = cur;
cur = cur + prev;
prev = temp;
}
return cur;
}
};
- 二進(jìn)制中1的個(gè)數(shù)
輸入一個(gè)整數(shù),輸出該數(shù)二進(jìn)制表示中1的個(gè)數(shù)。其中負(fù)數(shù)用補(bǔ)碼表示。
class Solution {
public:
int NumberOf1(int n) {
int res = 0;
while (n) {
n = n & (n - 1);
res++;
}
return res;
}
};
- 數(shù)值的整數(shù)次方
給定一個(gè)double類型的浮點(diǎn)數(shù)base和int類型的整數(shù)exponent。求base的exponent次方。
class Solution {
public:
double Power(double base, int exponent) {
double result = 1.0;
if (base == 0 && exponent < 0) {
return 0;
}
for (int i = 0; i < abs(exponent); i++) {
result *= base;
}
if (exponent < 0) {
result = 1 / result;
}
return result;
}
};
- 調(diào)整數(shù)組順序使奇數(shù)位于偶數(shù)前面
輸入一個(gè)整數(shù)數(shù)組,實(shí)現(xiàn)一個(gè)函數(shù)來調(diào)整該數(shù)組中數(shù)字的順序,使得所有的奇數(shù)位于數(shù)組的前半部分,所有的偶數(shù)位于數(shù)組的后半部分,并保證奇數(shù)和奇數(shù),偶數(shù)和偶數(shù)之間的相對位置不變。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void reOrderArray(vector<int> &array) {
stable_partition(array.begin(), array.end(),
[](int a) { return (a & 1) == 1; });
}
};
- 鏈表中倒數(shù)第k個(gè)結(jié)點(diǎn)
輸入一個(gè)鏈表,輸出該鏈表中倒數(shù)第k個(gè)結(jié)點(diǎn)。
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *FindKthToTail(ListNode *pListHead, unsigned int k) {
if (pListHead == NULL || k == 0) {
return nullptr;
}
int n = k;
auto faster = pListHead, walker = pListHead;
while (faster && n--) {
faster = faster->next;
}
if (faster == NULL && n != 0) {
return NULL;
}
while (faster) {
walker = walker->next;
faster = faster->next;
}
return walker;
}
};
- 反轉(zhuǎn)鏈表
輸入一個(gè)鏈表,反轉(zhuǎn)鏈表后,輸出新鏈表的表頭。
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution_0 {
public:
ListNode *ReverseList(ListNode *pHead) {
if (pHead == NULL || pHead->next == NULL) {
return pHead;
}
ListNode *pre = NULL, *cur = pHead;
while (cur) {
auto temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
class Solution {
public:
ListNode *ReverseList(ListNode *pHead) {
if (pHead == NULL || pHead->next == NULL) {
return pHead;
}
auto next = pHead->next;
auto p = ReverseList(next);
next->next = pHead;
pHead->next = NULL;
return p;
}
};
- 合并兩個(gè)排序的鏈表
輸入兩個(gè)單調(diào)遞增的鏈表,輸出兩個(gè)鏈表合成后的鏈表,當(dāng)然我們需要合成后的鏈表滿足單調(diào)不減規(guī)則。
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *Merge(ListNode *pHead1, ListNode *pHead2) {
ListNode *result = new ListNode(0);
auto current = result;
while (pHead1 && pHead2) {
if (pHead1->val < pHead2->val) {
current->next = pHead1;
pHead1 = pHead1->next;
} else {
current->next = pHead2;
pHead2 = pHead2->next;
}
current = current->next;
}
current->next = pHead1 ? pHead1 : pHead2;
return result->next;
}
};
- 樹的子結(jié)構(gòu)
輸入兩棵二叉樹A,B,判斷B是不是A的子結(jié)構(gòu)。(ps:我們約定空樹不是任意一個(gè)樹的子結(jié)構(gòu))
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// lc572題
class Solution_0 {
public:
bool isSubtree(TreeNode *s, TreeNode *t) {
if (isSameTree(s, t)) {
return true;
}
if (s != NULL && ((isSubtree(s->left, t)) || isSubtree(s->right, t))) {
return true;
}
return false;
}
bool isSameTree(TreeNode *t1, TreeNode *t2) {
if (t1 != NULL && t2 != NULL && t1->val == t2->val) {
return isSameTree(t1->left, t2->left) &&
isSameTree(t1->right, t2->right);
}
return t1 == NULL && t2 == NULL;
}
};
- 二叉樹的鏡像
操作給定的二叉樹,將其變換為源二叉樹的鏡像。
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if (pRoot) {
Mirror(pRoot->left);
Mirror(pRoot->right);
swap(pRoot->left, pRoot->right);
}
}
};
- 順時(shí)針打印矩陣
輸入一個(gè)矩陣,按照從外向里以順時(shí)針的順序依次打印出每一個(gè)數(shù)字,例如,如果輸入如下4 X 4矩陣: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 則依次打印出數(shù)字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> printMatrix(vector<vector<int>> &matrix) {
vector<int> res;
vector<vector<int>> dirs{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
vector<int> steps = {(int)matrix[0].size(), (int)matrix.size() - 1};
int idir = 0;
int h = 0, v = -1;
while (steps[idir % 2]) {
for (int i = 0; i < steps[idir % 2]; i++) {
h += dirs[idir][0];
v += dirs[idir][1];
res.push_back(matrix[h][v]);
}
steps[idir % 2]--;
idir = (idir + 1) % 4;
}
return res;
}
};
- 包含min函數(shù)的棧
定義棧的數(shù)據(jù)結(jié)構(gòu),請?jiān)谠擃愋椭袑?shí)現(xiàn)一個(gè)能夠得到棧中所含最小元素的min函數(shù)(時(shí)間復(fù)雜度應(yīng)為O(1))。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void push(int value) {
if (value <= minNum) {
stk.push(minNum);
minNum = value;
}
stk.push(value);
}
void pop() {
if (stk.top() == minNum) {
stk.pop();
minNum = stk.top();
}
stk.pop();
}
int top() { return stk.top(); }
int min() { return minNum; }
private:
stack<int> stk;
int minNum = INT_MAX;
};
- 棧的壓入、彈出序列
輸入兩個(gè)整數(shù)序列,第一個(gè)序列表示棧的壓入順序,請判斷第二個(gè)序列是否可能為該棧的彈出順序。假設(shè)壓入棧的所有數(shù)字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,序列4,5,3,2,1是該壓棧序列對應(yīng)的一個(gè)彈出序列,但4,3,5,1,2就不可能是該壓棧序列的彈出序列。(注意:這兩個(gè)序列的長度是相等的)
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool IsPopOrder(vector<int> pushV, vector<int> popV) {
stack<int> stk;
int j = 0;
for (int i = 0; i < pushV.size(); i++) {
stk.push(pushV[i]);
while (!stk.empty() && stk.top() == popV[j]) {
stk.pop();
j++;
}
}
return j == popV.size();
}
};
- 從上往下打印二叉樹
從上往下打印出二叉樹的每個(gè)節(jié)點(diǎn),同層節(jié)點(diǎn)從左至右打印。
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode *root) {
queue<TreeNode *> q;
vector<int> res;
if (root != NULL) {
q.push(root);
}
while (!q.empty()) {
int m = q.size();
for (int i = 0; i < m; i++) {
auto it = q.front();
res.push_back(it->val);
q.pop();
if (it->left) {
q.push(it->left);
}
if (it->right) {
q.push(it->right);
}
}
}
return res;
}
};
- 二叉搜索樹的后序遍歷序列
輸入一個(gè)整數(shù)數(shù)組,判斷該數(shù)組是不是某二叉搜索樹的后序遍歷的結(jié)果。如果是則輸出Yes,否則輸出No。假設(shè)輸入的數(shù)組的任意兩個(gè)數(shù)字都互不相同。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
if (sequence.empty()) {
return false;
}
return helper(sequence, 0, sequence.size() - 1);
}
bool helper(vector<int> &sequence, int left, int right) {
if (left >= right) {
return true;
}
int i = right - 1;
while (i >= left && sequence[i] > sequence[right]) {
i--;
}
for (int j = i; j >= left; j--) {
if (sequence[j] > sequence[right]) {
return false;
}
}
return helper(sequence, left, i) && helper(sequence, i + 1, right - 1);
}
};
- 二叉樹中和為某一值的路徑
輸入一顆二叉樹的跟節(jié)點(diǎn)和一個(gè)整數(shù),打印出二叉樹中結(jié)點(diǎn)值的和為輸入整數(shù)的所有路徑。路徑定義為從樹的根結(jié)點(diǎn)開始往下一直到葉結(jié)點(diǎn)所經(jīng)過的結(jié)點(diǎn)形成一條路徑。(注意: 在返回值的list中,數(shù)組長度大的數(shù)組靠前)
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<vector<int>> FindPath(TreeNode *root, int expectNumber) {
vector<vector<int>> res;
vector<int> path;
helper(root, expectNumber, 0, res, path);
return res;
}
void helper(TreeNode *root, int expectNumber, int current,
vector<vector<int>> &res, vector<int> &path) {
if (root) {
current += root->val;
path.push_back(root->val);
if (root->left == nullptr && root->right == nullptr &&
current == expectNumber) {
res.push_back(path);
}
helper(root->left, expectNumber, current, res, path);
helper(root->right, expectNumber, current, res, path);
path.pop_back();
}
}
};
- 復(fù)制鏈表的復(fù)制
輸入一個(gè)復(fù)雜鏈表(每個(gè)節(jié)點(diǎn)中有節(jié)點(diǎn)值,以及兩個(gè)指針,一個(gè)指向下一個(gè)節(jié)點(diǎn),另一個(gè)特殊指針指向任意一個(gè)節(jié)點(diǎn)),返回結(jié)果為復(fù)制后復(fù)雜鏈表的head。(注意,輸出結(jié)果中請不要返回參數(shù)中的節(jié)點(diǎn)引用,否則判題程序會直接返回空)
#include <bits/stdc++.h>
using namespace std;
struct RandomListNode {
int label;
RandomListNode *next, *random;
RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};
// lc138題
class Solution_1 {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
unordered_map<RandomListNode *, RandomListNode *> dir;
RandomListNode *current = head;
while (current) {
dir[current] = new RandomListNode(current->label);
current = current->next;
}
current = head;
while (current) {
dir[current]->next = current->next ? dir[current->next] : NULL;
dir[current]->random =
current->random ? dir[current->random] : NULL;
current = current->next;
}
return dir[head];
}
};
class Solution_2 {
public:
RandomListNode *copyRandomList(RandomListNode *head) { return clone(head); }
RandomListNode *clone(RandomListNode *head) {
if (head == NULL) {
return head;
}
if (dir.count(head)) {
return dir[head];
}
RandomListNode *root = new RandomListNode(head->label);
dir[head] = root;
root->next = clone(head->next);
root->random = clone(head->random);
return root;
}
private:
unordered_map<RandomListNode *, RandomListNode *> dir;
};
- 二叉搜索樹與雙向鏈表
輸入一棵二叉搜索樹,將該二叉搜索樹轉(zhuǎn)換成一個(gè)排序的雙向鏈表。要求不能創(chuàng)建任何新的結(jié)點(diǎn),只能調(diào)整樹中結(jié)點(diǎn)指針的指向。
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode *Convert(TreeNode *root) {
if (root == nullptr) {
return nullptr;
}
TreeNode *current = nullptr;
helper(root, current);
while (current->left) {
current = current->left;
}
return current;
}
void helper(TreeNode *root, TreeNode *&pre) {
if (root == nullptr) {
return;
}
helper(root->left, pre);
root->left = pre;
if (pre) {
pre->right = root;
}
pre = root;
helper(root->right, pre);
}
};
- 字符串的排列
輸入一個(gè)字符串,按字典序打印出該字符串中字符的所有排列。例如輸入字符串a(chǎn)bc,則打印出由字符a,b,c所能排列出來的所有字符串a(chǎn)bc,acb,bac,bca,cab和cba。
class Solution {
public:
vector<string> Permutation(string str) {
if (str == "") {
return {};
}
vector<string> res;
do {
res.push_back(str);
} while (next_permutation(str.begin(), str.end()));
return res;
}
};
- 數(shù)組中出現(xiàn)次數(shù)超過一半的數(shù)字
數(shù)組中有一個(gè)數(shù)字出現(xiàn)的次數(shù)超過數(shù)組長度的一半,請找出這個(gè)數(shù)字。例如輸入一個(gè)長度為9的數(shù)組{1,2,3,2,2,2,5,4,2}。由于數(shù)字2在數(shù)組中出現(xiàn)了5次,超過數(shù)組長度的一半,因此輸出2。如果不存在則輸出0。
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
int counter = 0, m = numbers.size();
int target = 0;
for (int i = 0; i < m; i++) {
if (counter == 0) {
target = numbers[i];
}
if (target == numbers[i]) {
counter++;
} else {
counter--;
}
}
return count(numbers.begin(), numbers.end(), target) > m / 2 ? target
: 0;
}
};
- 最小的K個(gè)數(shù)
輸入n個(gè)整數(shù),找出其中最小的K個(gè)數(shù)。例如輸入4,5,1,6,2,7,3,8這8個(gè)數(shù)字,則最小的4個(gè)數(shù)字是1,2,3,4,。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
int m = input.size();
if (k <= 0 || k > m) {
return {};
}
priority_queue<int, vector<int>, less<int>> q;
for (int i = 0; i < m; i++) {
if (q.size() < k) {
q.push(input[i]);
} else if (q.top() > input[i]) {
q.pop();
q.push(input[i]);
}
}
vector<int> res;
while (!q.empty()) {
res.push_back(q.top());
q.pop();
}
return res;
}
};
- 連續(xù)子數(shù)組的最大和
HZ偶爾會拿些專業(yè)問題來忽悠那些非計(jì)算機(jī)專業(yè)的同學(xué)。今天測試組開完會后,他又發(fā)話了:在古老的一維模式識別中,常常需要計(jì)算連續(xù)子向量的最大和,當(dāng)向量全為正數(shù)的時(shí)候,問題很好解決。但是,如果向量中包含負(fù)數(shù),是否應(yīng)該包含某個(gè)負(fù)數(shù),并期望旁邊的正數(shù)會彌補(bǔ)它呢?例如:{6,-3,-2,7,-15,1,2,2},連續(xù)子向量的最大和為8(從第0個(gè)開始,到第3個(gè)為止)。給一個(gè)數(shù)組,返回它的最大連續(xù)子序列的和,你會不會被他忽悠???(子向量的長度至少是1)
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int FindGreatestSumOfSubArray(vector<int> array) {
int sum = 0, max_sum = INT_MIN;
int m = array.size();
for (int i = 0; i < m; i++) {
sum = max(sum + array[i], array[i]);
max_sum = max(max_sum, sum);
}
return max_sum;
}
};
- 整數(shù)中1出現(xiàn)的次數(shù)
求出1-13的整數(shù)中1出現(xiàn)的次數(shù),并算出100~1300的整數(shù)中1出現(xiàn)的次數(shù)?為此他特別數(shù)了一下1-13中包含1的數(shù)字有1、10、11、12、13因此共出現(xiàn)6次,但是對于后面問題他就沒轍了。ACMer希望你們幫幫他,并把問題更加普遍化,可以很快的求出任意非負(fù)整數(shù)區(qū)間中1出現(xiàn)的次數(shù)(從1 到 n 中1出現(xiàn)的次數(shù))。
// lc233題
// https://leetcode.com/problems/number-of-digit-one/discuss/64381/4-lines-olog-n-cjavapython
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n) {
if (n <= 0) {
return 0;
}
int res = 0;
for (long long m = 1; m <= n; m *= 10) {
int a = n / m, b = n % m;
res += (a + 8) / 10 * m + (a % 10 == 1) * (b + 1);
}
return res;
}
};
- 把數(shù)組排成最小的數(shù)
輸入一個(gè)正整數(shù)數(shù)組,把數(shù)組里所有數(shù)字拼接起來排成一個(gè)數(shù),打印能拼接出的所有數(shù)字中最小的一個(gè)。例如輸入數(shù)組{3,32,321},則打印出這三個(gè)數(shù)字能排成的最小數(shù)字為321323。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string PrintMinNumber(vector<int> numbers) {
sort(numbers.begin(), numbers.end(), [](int a, int b) {
string str_a = to_string(a), str_b = to_string(b);
return str_a + str_b < str_b + str_a;
});
string res;
int m = numbers.size();
for (int i = 0; i < m; i++) {
res += to_string(numbers[i]);
}
return res;
}
};
- 丑數(shù)
把只包含質(zhì)因子2、3和5的數(shù)稱作丑數(shù)(Ugly Number)。例如6、8都是丑數(shù),但14不是,因?yàn)樗|(zhì)因子7。 習(xí)慣上我們把1當(dāng)做是第一個(gè)丑數(shù)。求按從小到大的順序的第N個(gè)丑數(shù)。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int GetUglyNumber_Solution(int index) {
if (index <= 0) {
return 0;
}
vector<int> nums(index, 0);
nums[0] = 1;
int one = 0, two = 0, three = 0;
for (int i = 1; i < index; i++) {
nums[i] = min(nums[one] * 2, min(nums[two] * 3, nums[three] * 5));
if (nums[one] * 2 == nums[i]) {
one++;
}
if (nums[two] * 3 == nums[i]) {
two++;
}
if (nums[three] * 5 == nums[i]) {
three++;
}
}
return nums[index - 1];
}
};
- 第一個(gè)只出現(xiàn)一次的字符位置
在一個(gè)字符串(0<=字符串長度<=10000,全部由字母組成)中找到第一個(gè)只出現(xiàn)一次的字符,并返回它的位置, 如果沒有則返回 -1(需要區(qū)分大小寫).
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int FirstNotRepeatingChar(string str) {
unordered_map<char, int> dir;
int m = str.size();
for (int i = 0; i < m; i++) {
dir[str[i]]++;
}
for (int i = 0; i < m; i++) {
if (dir[str[i]] == 1) {
return i;
}
}
return -1;
}
};
- 數(shù)組中的逆序?qū)?br>
在數(shù)組中的兩個(gè)數(shù)字,如果前面一個(gè)數(shù)字大于后面的數(shù)字,則這兩個(gè)數(shù)字組成一個(gè)逆序?qū)?。輸入一個(gè)數(shù)組,求出這個(gè)數(shù)組中的逆序?qū)Φ目倲?shù)P。并將P對1000000007取模的結(jié)果輸出。 即輸出P%1000000007
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int InversePairs(vector<int> data) {
int m = data.size();
vector<int> copy(m, 0);
return merge_pair(data, copy, 0, m - 1);
}
long merge_pair(vector<int> &data, vector<int> ©, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
long left_result = merge_pair(data, copy, left, mid);
long right_result = merge_pair(data, copy, mid + 1, right);
long other = merge_two_arr(data, copy, left, mid, right);
return (left_result + right_result + other) % 1000000007;
}
return 0;
}
long merge_two_arr(vector<int> &data, vector<int> ©, int left, int mid,
int right) {
long result = 0;
int i = mid, j = right, k = right;
while (i >= left && j > mid) {
if (data[i] > data[j]) {
copy[k--] = data[i--];
result += j - mid;
} else {
copy[k--] = data[j--];
}
}
while (i >= left) {
copy[k--] = data[i--];
}
while (j > mid) {
copy[k--] = data[j--];
}
for (int i = left; i <= right; i++) {
data[i] = copy[i];
}
return result;
}
};
- 兩個(gè)鏈表的第一個(gè)公共結(jié)點(diǎn)
輸入兩個(gè)鏈表,找出它們的第一個(gè)公共結(jié)點(diǎn)。
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *FindFirstCommonNode(ListNode *pHead1, ListNode *pHead2) {
int m = 0, n = 0;
auto current1 = pHead1, current2 = pHead2;
while (current1) {
current1 = current1->next;
m++;
}
while (current2) {
current2 = current2->next;
n++;
}
if (m < n) {
swap(pHead1, pHead2);
}
int diff = abs(m - n);
current1 = pHead1, current2 = pHead2;
while (diff--) {
current1 = current1->next;
}
while (current1 != current2) {
current1 = current1->next;
current2 = current2->next;
}
return current1;
}
};
- 數(shù)字在排序數(shù)組中出現(xiàn)的次數(shù)
統(tǒng)計(jì)一個(gè)數(shù)字在排序數(shù)組中出現(xiàn)的次數(shù)。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int GetNumberOfK(vector<int> data, int k) {
auto it1 = lower_bound(data.begin(), data.end(), k);
auto it2 = upper_bound(data.begin(), data.end(), k);
return it2 - it1;
}
};
- 二叉樹的深度
輸入一棵二叉樹,求該樹的深度。從根結(jié)點(diǎn)到葉結(jié)點(diǎn)依次經(jīng)過的結(jié)點(diǎn)(含根、葉結(jié)點(diǎn))形成樹的一條路徑,最長路徑的長度為樹的深度。
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int TreeDepth(TreeNode *pRoot) {
if (pRoot == nullptr) {
return 0;
}
return 1 + max(TreeDepth(pRoot->left), TreeDepth(pRoot->right));
}
};
- 平衡二叉樹
輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool IsBalanced_Solution(TreeNode *pRoot) {
int deep = 0;
return IsBalanced_Solution(pRoot, deep);
}
bool IsBalanced_Solution(TreeNode *root, int &deep) {
if (root == nullptr) {
deep = 0;
return true;
}
int left = 0, right = 0;
if (IsBalanced_Solution(root->left, left) &&
IsBalanced_Solution(root->right, right) && abs(left - right) <= 1) {
deep = max(left, right) + 1;
return true;
}
return false;
}
};
- 數(shù)組中只出現(xiàn)一次的數(shù)字
一個(gè)整型數(shù)組里除了兩個(gè)數(shù)字之外,其他的數(shù)字都出現(xiàn)了偶數(shù)次。請寫程序找出這兩個(gè)只出現(xiàn)一次的數(shù)字。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void FindNumsAppearOnce(vector<int> data, int *num1, int *num2) {
int m = data.size();
if (m < 2) {
return;
}
int res = 0;
for (int i = 0; i < m; i++) {
res ^= data[i];
}
int firstBit = first_bit(res);
*num1 = 0, *num2 = 0;
int bit_s = 1 << firstBit;
for (int i = 0; i < m; i++) {
if (data[i] & bit_s) {
*num1 ^= data[i];
} else {
*num2 ^= data[i];
}
}
}
int first_bit(int num) {
int index = 0;
while (num && (num & 1) == 0) {
num >>= 1;
index++;
}
return index;
}
};
- 和為S的連續(xù)正數(shù)序列
小明很喜歡數(shù)學(xué),有一天他在做數(shù)學(xué)作業(yè)時(shí),要求計(jì)算出9~16的和,他馬上就寫出了正確答案是100。但是他并不滿足于此,他在想究竟有多少種連續(xù)的正數(shù)序列的和為100(至少包括兩個(gè)數(shù))。沒多久,他就得到另一組連續(xù)正數(shù)和為100的序列:18,19,20,21,22。現(xiàn)在把問題交給你,你能不能也很快的找出所有和為S的連續(xù)正數(shù)序列? Good Luck!
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> FindContinuousSequence(int sum) {
vector<vector<int>> res;
int left = 1, right = 2;
int current_sum = left + right;
while (left < (1 + sum) / 2) {
if (current_sum >= sum) {
if (current_sum == sum) {
vector<int> re;
for (int i = left; i <= right; i++) {
re.push_back(i);
}
res.push_back(re);
}
current_sum -= left;
left++;
} else {
right++;
current_sum += right;
}
}
return res;
}
};
- 和為S的兩個(gè)數(shù)字
輸入一個(gè)遞增排序的數(shù)組和一個(gè)數(shù)字S,在數(shù)組中查找兩個(gè)數(shù),使得他們的和正好是S,如果有多對數(shù)字的和等于S,輸出兩個(gè)數(shù)的乘積最小的。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> FindNumbersWithSum(vector<int> array, int sum) {
int m = array.size();
vector<int> res;
for (int i = 0, j = m - 1; i < j;) {
int c_sum = array[i] + array[j];
if (c_sum < sum) {
i++;
} else if (c_sum > sum) {
j--;
} else {
res = {array[i], array[j]};
i++, j--;
break;
}
}
return res;
}
};
- 左旋轉(zhuǎn)字符串
匯編語言中有一種移位指令叫做循環(huán)左移(ROL),現(xiàn)在有個(gè)簡單的任務(wù),就是用字符串模擬這個(gè)指令的運(yùn)算結(jié)果。對于一個(gè)給定的字符序列S,請你把其循環(huán)左移K位后的序列輸出。例如,字符序列S=”abcXYZdef”,要求輸出循環(huán)左移3位后的結(jié)果,即“XYZdefabc”。是不是很簡單?OK,搞定它!
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string LeftRotateString(string str, int n) {
if (str.empty() || str.size() < n) {
return str;
}
reverse(str.begin(), str.begin() + n);
reverse(str.begin() + n, str.end());
reverse(str.begin(), str.end());
return str;
}
};
- 翻轉(zhuǎn)單詞順序列
??妥罱鼇砹艘粋€(gè)新員工Fish,每天早晨總是會拿著一本英文雜志,寫些句子在本子上。同事Cat對Fish寫的內(nèi)容頗感興趣,有一天他向Fish借來翻看,但卻讀不懂它的意思。例如,“student. a am I”。后來才意識到,這家伙原來把句子單詞的順序翻轉(zhuǎn)了,正確的句子應(yīng)該是“I am a student.”。Cat對一一的翻轉(zhuǎn)這些單詞順序可不在行,你能幫助他么?
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string ReverseSentence(string str) {
vector<string> res;
int m = str.size();
if (str.find_first_not_of(' ') == string::npos) {
return str;
}
for (int i = 0; i < m; i++) {
if (str[i] != ' ') {
int j = i;
while (i < m && str[i] != ' ') {
i++;
}
res.push_back(str.substr(j, i - j));
}
}
string str_res;
reverse(res.begin(), res.end());
int n = res.size();
for (int i = 0; i < n - 1; i++) {
str_res += res[i] + " ";
}
str_res += (n != 0 ? res[n - 1] : "");
return str_res;
}
};
- 撲克牌順子
LL今天心情特別好,因?yàn)樗ベI了一副撲克牌,發(fā)現(xiàn)里面居然有2個(gè)大王,2個(gè)小王(一副牌原本是54張_)...他隨機(jī)從中抽出了5張牌,想測測自己的手氣,看看能不能抽到順子,如果抽到的話,他決定去買體育彩票,嘿嘿??!“紅心A,黑桃3,小王,大王,方片5”,“Oh My God!”不是順子.....LL不高興了,他想了想,決定大\小 王可以看成任何數(shù)字,并且A看作1,J為11,Q為12,K為13。上面的5張牌就可以變成“1,2,3,4,5”(大小王分別看作2和4),“So Lucky!”。LL決定去買體育彩票啦。 現(xiàn)在,要求你使用這幅牌模擬上面的過程,然后告訴我們LL的運(yùn)氣如何, 如果牌能組成順子就輸出true,否則就輸出false。為了方便起見,你可以認(rèn)為大小王是0。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool IsContinuous(vector<int> numbers) {
if (numbers.empty()) {
return false;
}
sort(numbers.begin(), numbers.end());
int m = numbers.size();
int num_zero = 0;
for (int i = 0; i < m && numbers[i] == 0; i++) {
num_zero++;
}
for (int i = num_zero + 1; i < m; i++) {
if (numbers[i] == numbers[i - 1]) {
return false;
}
num_zero -= (numbers[i] - numbers[i - 1] - 1);
}
return num_zero >= 0;
}
};
- 孩子們的游戲
每年六一兒童節(jié),??投紩?zhǔn)備一些小禮物去看望孤兒院的小朋友,今年亦是如此。HF作為??偷馁Y深元老,自然也準(zhǔn)備了一些小游戲。其中,有個(gè)游戲是這樣的:首先,讓小朋友們圍成一個(gè)大圈。然后,他隨機(jī)指定一個(gè)數(shù)m,讓編號為0的小朋友開始報(bào)數(shù)。每次喊到m-1的那個(gè)小朋友要出列唱首歌,然后可以在禮品箱中任意的挑選禮物,并且不再回到圈中,從他的下一個(gè)小朋友開始,繼續(xù)0...m-1報(bào)數(shù)....這樣下去....直到剩下最后一個(gè)小朋友,可以不用表演,并且拿到牛客名貴的“名偵探柯南”典藏版(名額有限哦!!_)。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int LastRemaining_Solution(int n, int m) {
if (n < 1 || m < 1) {
return -1;
}
int last = 0;
for (int i = 2; i <= n; i++) {
last = (last + m) % i;
}
return last;
}
};
- 求1+2+3+...+n
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等關(guān)鍵字及條件判斷語句(A?B:C)。
class Solution {
public:
int Sum_Solution(int n) {
int res = n;
n && (res += Sum_Solution(n - 1));
return res;
}
};
- 不用加減乘除做加法
寫一個(gè)函數(shù),求兩個(gè)整數(shù)之和,要求在函數(shù)體內(nèi)不得使用+、-、*、/四則運(yùn)算符號。
class Solution {
public:
int Add(int num1, int num2) {
int sum = 0, carry = 0;
do {
sum = num1 ^ num2;
carry = (num1 & num2) << 1;
num1 = sum;
num2 = carry;
} while (num2);
return num1;
}
};
- 把字符串轉(zhuǎn)換成整數(shù)
將一個(gè)字符串轉(zhuǎn)換成一個(gè)整數(shù)(實(shí)現(xiàn)Integer.valueOf(string)的功能,但是string不符合數(shù)字要求時(shí)返回0),要求不能使用字符串轉(zhuǎn)換整數(shù)的庫函數(shù)。 數(shù)值為0或者字符串不是一個(gè)合法的數(shù)值則返回0。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int StrToInt(string str) {
if (str.empty()) {
return 0;
}
int m = str.size(), num = 0;
int sign = str[0] == '-' ? -1 : 1;
for (int i = (str[0] == '-' || str[0] == '+' ? 1 : 0); i < m; i++) {
if (!isdigit(str[i])) {
return 0;
}
num = num * 10 + str[i] - '0';
}
return sign * num;
}
};
- 數(shù)組中重復(fù)的數(shù)字
在一個(gè)長度為n的數(shù)組里的所有數(shù)字都在0到n-1的范圍內(nèi)。 數(shù)組中某些數(shù)字是重復(fù)的,但不知道有幾個(gè)數(shù)字是重復(fù)的。也不知道每個(gè)數(shù)字重復(fù)幾次。請找出數(shù)組中任意一個(gè)重復(fù)的數(shù)字。 例如,如果輸入長度為7的數(shù)組{2,3,1,0,2,5,3},那么對應(yīng)的輸出是第一個(gè)重復(fù)的數(shù)字2。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool duplicate(int numbers[], int length, int *duplication) {
if (numbers == nullptr || length <= 0) {
return false;
}
for (int i = 0; i < length; i++) {
if (numbers[i] != i) {
if (numbers[i] == numbers[numbers[i]]) {
*duplication = numbers[i];
return true;
}
swap(numbers[i], numbers[numbers[i]]);
}
}
return false;
}
};
- 構(gòu)建乘積數(shù)組
給定一個(gè)數(shù)組A[0,1,...,n-1],請構(gòu)建一個(gè)數(shù)組B[0,1,...,n-1],其中B中的元素B[i]=A[0]A[1]...A[i-1]A[i+1]...A[n-1]。不能使用除法。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> multiply(const vector<int> &A) {
int m = A.size();
vector<int> left(m, 1), right(m, 1), res(m, 0);
for (int i = 1; i < m; i++) {
left[i] = left[i - 1] * A[i - 1];
}
for (int i = m - 2; i >= 0; i--) {
right[i] = right[i + 1] * A[i + 1];
}
for (int i = 0; i < m; i++) {
res[i] = left[i] * right[i];
}
return res;
}
};
- 正則表達(dá)式匹配
給定一個(gè)數(shù)組A[0,1,...,n-1],請構(gòu)建一個(gè)數(shù)組B[0,1,...,n-1],其中B中的元素B[i]=A[0]A[1]...A[i-1]A[i+1]...A[n-1]。不能使用除法。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool match(char *str, char *pattern) {
string s(str), p(pattern);
int m = s.length(), n = p.length();
vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));
dp[0][0] = true;
for (int i = 0; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (p[j - 1] != '*') {
dp[i][j] = i > 0 && dp[i - 1][j - 1] &&
(p[j - 1] == '.' || s[i - 1] == p[j - 1]);
} else {
dp[i][j] = dp[i][j - 2] ||
(i > 0 && dp[i - 1][j] &&
(s[i - 1] == p[j - 2] || p[j - 2] == '.'));
}
}
}
return dp[m][n];
}
};
- 表示數(shù)值的字符串
請實(shí)現(xiàn)一個(gè)函數(shù)用來判斷字符串是否表示數(shù)值(包括整數(shù)和小數(shù))。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示數(shù)值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
class Solution {
public:
bool isNumeric(char *str) {
bool sign = false, decimal = false, hasE = false;
int m = strlen(str);
for (int i = 0; i < m; i++) {
if (str[i] == 'e' || str[i] == 'E') {
if (i == m - 1 || hasE) {
return false;
}
hasE = true;
} else if (str[i] == '+' || str[i] == '-') {
if (sign && str[i - 1] != 'e' && str[i - 1] != 'E') {
return false;
}
if (!sign && i > 0 && str[i - 1] != 'e' && str[i - 1] != 'E') {
return false;
}
sign = true;
} else if (str[i] == '.') {
if (hasE || decimal) {
return false;
}
decimal = true;
} else if (str[i] < '0' || str[i] > '9') {
return false;
}
}
return true;
}
};
- 字符流中第一個(gè)不重復(fù)的字符
請實(shí)現(xiàn)一個(gè)函數(shù)用來找出字符流中第一個(gè)只出現(xiàn)一次的字符。例如,當(dāng)從字符流中只讀出前兩個(gè)字符"go"時(shí),第一個(gè)只出現(xiàn)一次的字符是"g"。當(dāng)從該字符流中讀出前六個(gè)字符“google"時(shí),第一個(gè)只出現(xiàn)一次的字符是"l"。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Insert one char from stringstream
void Insert(char ch) {
res.push_back(ch);
dir[ch]++;
}
// return the first appearence once char in current stringstream
char FirstAppearingOnce() {
int m = res.size();
for (int i = 0; i < m; i++) {
if (dir[res[i]] == 1) {
return res[i];
}
}
return '#';
}
private:
string res;
map<char, int> dir;
};
- 鏈表中環(huán)的入口結(jié)點(diǎn)
給一個(gè)鏈表,若其中包含環(huán),請找出該鏈表的環(huán)的入口結(jié)點(diǎn),否則,輸出null。
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *EntryNodeOfLoop(ListNode *pHead) {
auto faster = pHead, walker = pHead, entry = pHead;
while (faster && faster->next) {
faster = faster->next->next;
walker = walker->next;
if (faster == walker) {
while (entry != walker) {
walker = walker->next;
entry = entry->next;
}
return entry;
}
}
return NULL;
}
};
- 刪除鏈表中重復(fù)的結(jié)點(diǎn)
在一個(gè)排序的鏈表中,存在重復(fù)的結(jié)點(diǎn),請刪除該鏈表中重復(fù)的結(jié)點(diǎn),重復(fù)的結(jié)點(diǎn)不保留,返回鏈表頭指針。 例如,鏈表1->2->3->3->4->4->5 處理后為 1->2->5
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *deleteDuplication(ListNode *pHead) {
if (pHead == nullptr || pHead->next == nullptr) {
return pHead;
}
ListNode *result = new ListNode(-1);
result->next = pHead;
auto prev = result, current = pHead;
while (current) {
while (current->next && current->val == current->next->val) {
current = current->next;
}
if (prev->next == current) {
prev = current;
} else {
prev->next = current->next;
}
current = current->next;
}
return result->next;
}
};
- 二叉樹的下一個(gè)結(jié)點(diǎn)
給定一個(gè)二叉樹和其中的一個(gè)結(jié)點(diǎn),請找出中序遍歷順序的下一個(gè)結(jié)點(diǎn)并且返回。注意,樹中的結(jié)點(diǎn)不僅包含左右子結(jié)點(diǎn),同時(shí)包含指向父結(jié)點(diǎn)的指針。
#include <bits/stdc++.h>
using namespace std;
struct TreeLinkNode {
int val;
struct TreeLinkNode *left;
struct TreeLinkNode *right;
struct TreeLinkNode *next;
TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};
class Solution {
public:
TreeLinkNode *GetNext(TreeLinkNode *pNode) {
if (pNode == nullptr) {
return nullptr;
}
if (pNode->right) {
pNode = pNode->right;
while (pNode->left) {
pNode = pNode->left;
}
return pNode;
}
while (pNode->next) {
if (pNode->next->left == pNode) {
return pNode->next;
}
pNode = pNode->next;
}
return NULL;
}
};
- 對稱的二叉樹
請實(shí)現(xiàn)一個(gè)函數(shù),用來判斷一顆二叉樹是不是對稱的。注意,如果一個(gè)二叉樹同此二叉樹的鏡像是同樣的,定義其為對稱的。
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isSymmetrical(TreeNode *pRoot) {
if (pRoot != NULL) {
return isMirrorTree(pRoot->left, pRoot->right);
}
return true;
}
bool isMirrorTree(TreeNode *p, TreeNode *q) {
if (p == NULL || q == NULL)
return (p == q);
return p->val == q->val && isMirrorTree(p->left, q->right) &&
isMirrorTree(p->right, q->left);
}
};
- 按之字形順序打印二叉樹
請實(shí)現(xiàn)一個(gè)函數(shù)按照之字形打印二叉樹,即第一行按照從左到右的順序打印,第二層按照從右至左的順序打印,第三行按照從左到右的順序打印,其他行以此類推。
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<vector<int>> Print(TreeNode *pRoot) {
vector<vector<int>> res;
if (pRoot == nullptr) {
return res;
}
bool left_to_right = true;
queue<TreeNode *> q;
q.push(pRoot);
while (!q.empty()) {
int m = q.size();
vector<int> temp;
for (int i = 0; i < m; i++) {
auto e = q.front();
q.pop();
if (e->left) {
q.push(e->left);
}
if (e->right) {
q.push(e->right);
}
temp.push_back(e->val);
}
if (!left_to_right) {
reverse(temp.begin(), temp.end());
}
res.push_back(temp);
left_to_right = !left_to_right;
}
return res;
}
};
- 把二叉樹打印成多行
從上到下按層打印二叉樹,同一層結(jié)點(diǎn)從左至右輸出。每一層輸出一行。
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<vector<int>> Print(TreeNode *pRoot) {
vector<vector<int>> res;
if (pRoot == nullptr) {
return res;
}
queue<TreeNode *> q;
q.push(pRoot);
while (!q.empty()) {
int m = q.size();
vector<int> temp;
for (int i = 0; i < m; i++) {
auto e = q.front();
q.pop();
if (e->left) {
q.push(e->left);
}
if (e->right) {
q.push(e->right);
}
temp.push_back(e->val);
}
res.push_back(temp);
}
return res;
}
};
- 序列化二叉樹
請實(shí)現(xiàn)兩個(gè)函數(shù),分別用來序列化和反序列化二叉樹
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
char *Serialize(TreeNode *root) {
ostringstream out;
serialize(root, out);
char *result = new char[out.str().length() + 1];
strcpy(result, out.str().c_str());
return result;
}
void serialize(TreeNode *root, ostringstream &out) {
if (root == NULL) {
out << "# ";
return;
}
out << root->val << " ";
serialize(root->left, out);
serialize(root->right, out);
}
TreeNode *Deserialize(char *str) {
istringstream in(str);
return deserialize(in);
}
TreeNode *deserialize(istringstream &in) {
string word;
in >> word;
if (word == "#") {
return NULL;
}
TreeNode *root = new TreeNode(stoi(word));
root->left = deserialize(in);
root->right = deserialize(in);
return root;
}
};
- 二叉搜索樹的第k個(gè)結(jié)點(diǎn)
給定一棵二叉搜索樹,請找出其中的第k小的結(jié)點(diǎn)。例如, (5,3,7,2,4,6,8) 中,按結(jié)點(diǎn)數(shù)值大小順序第三小結(jié)點(diǎn)的值為4。
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode *res = nullptr;
TreeNode *KthNode(TreeNode *pRoot, int k) {
inorder(pRoot, k);
return res;
}
void inorder(TreeNode *root, int &k) {
if (!res && root && k > 0) {
inorder(root->left, k);
k--;
if (k == 0) {
res = root;
return;
}
inorder(root->right, k);
}
}
};
- 數(shù)據(jù)流中的中位數(shù)
#include <bits/stdc++.h>
using namespace std;
class MedianFinder {
public:
/** initialize your data structure here. */
MedianFinder() {}
void addNum(int num) {
min_heap.push(num);
max_heap.push(min_heap.top());
min_heap.pop();
if (max_heap.size() > min_heap.size()) {
auto temp = max_heap.top();
max_heap.pop();
min_heap.push(temp);
}
}
double findMedian() {
if (max_heap.size() == min_heap.size()) {
return (max_heap.top() + min_heap.top()) / 2.0;
} else {
return min_heap.top();
}
}
private:
priority_queue<int, vector<int>, less<int>> max_heap;
priority_queue<int, vector<int>, greater<int>> min_heap;
};
- 滑動(dòng)窗口的最大值
給定一個(gè)數(shù)組和滑動(dòng)窗口的大小,找出所有滑動(dòng)窗口里數(shù)值的最大值。例如,如果輸入數(shù)組{2,3,4,2,6,2,5,1}及滑動(dòng)窗口的大小3,那么一共存在6個(gè)滑動(dòng)窗口,他們的最大值分別為{4,4,6,6,6,5}; 針對數(shù)組{2,3,4,2,6,2,5,1}的滑動(dòng)窗口有以下6個(gè): {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> maxSlidingWindow(vector<int> &nums, int k) {
vector<int> res;
deque<int> dq;
int m = nums.size();
for (int i = 0; i < m; i++) {
while (!dq.empty() && dq.front() <= i - k) {
dq.pop_front();
}
while (!dq.empty() && nums[dq.back()] < nums[i]) {
dq.pop_back();
}
dq.push_back(i);
if (i >= k - 1) {
res.push_back(nums[dq.front()]);
}
}
return res;
}
};
- 矩陣中的路徑
請?jiān)O(shè)計(jì)一個(gè)函數(shù),用來判斷在一個(gè)矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個(gè)格子開始,每一步可以在矩陣中向左,向右,向上,向下移動(dòng)一個(gè)格子。如果一條路徑經(jīng)過了矩陣中的某一個(gè)格子,則之后不能再次進(jìn)入這個(gè)格子。 例如 a b c e s f c s a d e e 這樣的3 X 4 矩陣中包含一條字符串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因?yàn)樽址牡谝粋€(gè)字符b占據(jù)了矩陣中的第一行第二個(gè)格子之后,路徑不能再次進(jìn)入該格子。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool hasPath(char *matrix, int rows, int cols, char *str) {
if (matrix == nullptr || rows < 1 || cols < 1 || str == nullptr) {
return false;
}
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (helper(matrix, rows, cols, i, j, str, 0, visited)) {
return true;
}
}
}
return false;
}
bool helper(char *matrix, int rows, int cols, int ii, int jj, char *str,
int length, vector<vector<bool>> &visited) {
if (str[length] == '\0') {
return true;
}
if (!isInVaildBoardary(rows, cols, ii, jj) ||
matrix[ii * cols + jj] != str[length] || visited[ii][jj]) {
return false;
}
visited[ii][jj] = true;
for (int i = 0; i < direction.size(); i++) {
int xx = ii + direction[i][0];
int yy = jj + direction[i][1];
if (helper(matrix, rows, cols, xx, yy, str, length + 1, visited)) {
return true;
}
}
visited[ii][jj] = false;
return false;
}
bool isInVaildBoardary(int rows, int cols, int row, int col) {
int m = rows, n = cols;
if (row >= 0 && row < m && col >= 0 && col < n) {
return true;
}
return false;
}
private:
vector<vector<int>> direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
};
- 機(jī)器人的運(yùn)動(dòng)范圍
地上有一個(gè)m行和n列的方格。一個(gè)機(jī)器人從坐標(biāo)0,0的格子開始移動(dòng),每一次只能向左,右,上,下四個(gè)方向移動(dòng)一格,但是不能進(jìn)入行坐標(biāo)和列坐標(biāo)的數(shù)位之和大于k的格子。 例如,當(dāng)k為18時(shí),機(jī)器人能夠進(jìn)入方格(35,37),因?yàn)?+5+3+7 = 18。但是,它不能進(jìn)入方格(35,38),因?yàn)?+5+3+8 = 19。請問該機(jī)器人能夠達(dá)到多少個(gè)格子?
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int movingCount(int threshold, int rows, int cols) {
if (rows <= 0 || cols <= 0 || threshold < 0) {
return 0;
}
int res = 0;
vector<vector<bool>> visited(rows, vector<bool>(cols, 0));
helper(threshold, rows, cols, 0, 0, visited, res);
return res;
}
void helper(int threshold, int rows, int cols, int row, int col,
vector<vector<bool>> &visited, int &res) {
visited[row][col] = true;
res++;
for (int i = 0; i < direction.size(); i++) {
int xx = row + direction[i][0], yy = col + direction[i][1];
if (isInVaildBoardary(rows, cols, xx, yy) && !visited[xx][yy] &&
getDigit(xx, yy) <= threshold) {
helper(threshold, rows, cols, xx, yy, visited, res);
}
}
}
int getDigit(int row, int col) {
string s = to_string(row), s1 = to_string(col);
return accumulate(s.begin(), s.end(), 0,
[](int sum, char a) { return sum + a - '0'; }) +
accumulate(s1.begin(), s1.end(), 0,
[](int sum, char a) { return sum + a - '0'; });
}
bool isInVaildBoardary(int rows, int cols, int row, int col) {
int m = rows, n = cols;
if (row >= 0 && row < m && col >= 0 && col < n) {
return true;
}
return false;
}
private:
vector<vector<int>> direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
};