Contest 111 (题号941~944)(2019年1月19日,补充题解,主要是943题)

链接:https://leetcode.com/contest/weekly-contest-111

【941】Valid Mountain Array(第一题 3分)(google tag)

判断一个数组是不是 Mountain 数组。 Mountain 数组的定义是

A.length >= 3
There exists some i with 0 < i < A.length - 1 such that:
A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > A[B.length - 1]

题解: 先判断元素个数是不是比 3 大,然后想象两拨人爬山,这个定义就是看最后两拨人是不是爬到了同一个山顶。

 class Solution {
public:
bool validMountainArray(vector<int>& A) {
const int n = A.size();
int start = , end = n - ;
while (start + < n && A[start] < A[start+]) {
++start;
}
while (end - >= && A[end-] > A[end]) {
--end;
}
return start > && start == end && end < n-;
}
};

Delete Columns to Make Sorted(第二题 4分)

DI String Match(第三题 5分)

【943】Find the Shortest Superstring(第四题 8分)

Given an array A of strings, find any smallest string that contains each string in A as a substring.

We may assume that no string in A is substring of another string in A.

Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc" Note:
1 <= A.length <= 12
1 <= A[i].length <= 20

题解:本题可以看成旅行商问题,用状态压缩的动态规划来解。我们先给每个单词都标号,然后从word1到word2重合之后,word2长出来的长度就是图的权重。比如 word1 = abcd, word2 = bcdfsd, g[word1][word2] = 3.

然后我们想走过每一个单词,使得图的总权重最小。这个就是旅行商问题的定义。我们用一个二进制 11110111, 表示除了第三个单词不在,其他七个单词都存在。这个就是状态压缩。(用一个二进制表示一个set中的元素是否存在)

《挑战设计程序竞赛》3.4.1

假设我们现在已经访问过顶点的集合是S,当前所在的顶点为 v, 用 dp[S][v]表示从v出发访问剩余的所有顶点,最终回到顶点0的路径的权重总和的最小值。由于从 v 出发可以移动到任意的一个节点 u 不属于 S,因此有下面的递推式。

dp[V][0] = 0;

dp[S][v] = min{dp[S U {u}][u] + d(v, u) | u 不属于 S }

 class Solution {
public:
const int MAX = ;
string shortestSuperstring(vector<string>& A) {
const int n = A.size();
vector<vector<int>> g = initGraph(A);
vector<vector<int>> dp( << MAX, vector<int>(n, INT_MAX));
int path[ << MAX][MAX] = {INT_MAX};
int minLen = INT_MAX, last = -;
for (int S = ; S < << n; ++S) {
for (int j = ; j < n; ++j) {
if ((S & ( << j)) > ) { //一定要加括号,不然先算 (1 << j) > 0 再算 位运算
int prev = S - ( << j);
if (prev == ) {
dp[S][j] = A[j].size();
} else {
for (int k = ; k < n; ++k) {
if (dp[prev][k] < INT_MAX && dp[prev][k] + g[k][j] < dp[S][j]) {
dp[S][j] = min(dp[prev][k] + g[k][j], dp[S][j]);
path[S][j] = k;
}
}
}
}
if (S == (( << n) - ) && dp[S][j] < minLen) {
minLen = dp[S][j];
last = j;
}
}
}
// build string.
string ret = "";
int index = last, pre = last, state = ( << n) -;
vector<int> seq(n);
for (int i = n-; i >= ; --i) {
seq[i] = index;
pre = path[state][index];
state = state - ( << index);
// printf ("index = %d, state = %d, pre = %d \n", index, state, pre);
index = pre;
} ret = A[seq[]];
for (int i = ; i < n; ++i) {
string str = A[seq[i]];
ret += str.substr(str.size() - g[seq[i-]][seq[i]]);
}
return ret;
}
vector<vector<int>> initGraph(vector<string>& A) {
const int n = A.size();
vector<vector<int>> g(n, vector<int>(n, ));
for (int i = ; i < A.size(); ++i) {
for (int j = i; j < A.size(); ++j) {
g[i][j] = cal(A[i], A[j]);
g[j][i] = cal(A[j], A[i]);
}
}
return g;
}
int cal(string s1, string s2) { //A[u] = s1, A[v] = s2
const int n1 = s1.size(), n2 = s2.size();
int ret = n2;
for (int k = ; k < n1; ++k) {
string sub1 = s1.substr(k); // len = n1 - k
string sub2 = s2.substr(, n1-k); // len = n1 - k;
if (sub1 == sub2) {
ret = min(ret, n2 - n1 + k);
break;
}
}
return ret;
}
void print(vector<vector<int>>& g) {
const int n = g.size();
const int m = g[].size();
for (int i = ; i < n; ++i) {
for (int j = ; j < m; ++j) {
printf("%d ", g[i][j]);
}
printf("\n");
}
}
};

Contest 112(2018年11月25日)(题号945~948)

比赛情况记录:这场有点像是贪心专题了orz,结果:1/4,ranking:1383/3195,第一题懵逼的原因是 5-3=3?==。这场真的没有一题难题,然后就是不会做。这就比较尴尬了。

链接:https://leetcode.com/contest/weekly-contest-112

【945】Minimum Increment to Make Array Unique(第一题 5分)

题意是给了一个数组有重复数字,目标是把数组中的元素都变成 unique 的,游戏规则是移动一步可以把一个数字加一。问最少移动几步能把所有数字unique化。

题解:先排序,然后按照排序的数字递增,缺几个就加几。

 class Solution {
public:
int minIncrementForUnique(vector<int>& A) {
sort(A.begin(), A.end());
const int n = A.size();
int res = ;
for (int i = ; i < n; ++i) {
if (A[i] > A[i-]) {continue;}
int newAi = A[i-]+;
res += newAi - A[i];
A[i] = newAi;
}
return res;
}
};

【946】Validate Stack Sequences(第二题 6分)(我没记错的话这题应该是剑指offer原题)

给了两个 distinct 的序列,问一个作为栈的 push 序列的话,另外一个是否能作为 pop 序列。

题解:直接模拟栈的行为。

 class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
const int n = pushed.size();
stack<int> stk;
int p1 = , p2 = ;
while (p1 < n && p2 < n) {
while (stk.empty() || stk.top() != popped[p2]) {
stk.push(pushed[p1++]);
}
while (!stk.empty() && stk.top() == popped[p2]) {
stk.pop();
++p2;
}
}
while (!stk.empty() && stk.top() == popped[p2]) {
stk.pop();
++p2;
}
return stk.empty();
}
};

【947】Most Stones Removed with Same Row or Column(第三题 6分)(2019年1月30日,谷歌tag复习)

【948】Bag of Tokens(第四题 6分)(2018年12月9日,算法群每日一题,补充的周赛解题报告)

题意是给了一个tokens的数组,和一个原始的power P,游戏规则如下:(1)用 tokens[i] 的 power 可以换 1 point; (2) 用 1 point 也可以换 tokens[i] 的power。问最多能换多少 point。

题解:greedy + 2 pointers。排序之后用2 pointers 两遍夹逼。前面的pointer用来换point(一直往前直到当前的power换不起point了), 后面的pointer用来换power。

 class Solution {
public:
int bagOfTokensScore(vector<int>& tokens, int P) {
const int n = tokens.size();
sort(tokens.begin(), tokens.end()); //1. sort
int points = , ret = ;
//2 .2 pointers, boundary
int p1 = , p2 = n - ;
while (p1 <= p2) {
int preP1 = p1, preP2 = p2;
while (p1 <= p2 && P >= tokens[p1]) {
points += ;
P -= tokens[p1++];
}
ret = max(points, ret);
if (p1 <= p2 && points >= ) {
points -= ;
P += tokens[p2--];
}
if (p1 == preP1 && p2 == preP2) {
break;
}
}
return ret;
}
};

Contest 113 (2018年12月2日)(题号949~952)

比赛情况记录:结果:3/4, ranking: 708/3549。起床晚了,第一题手残调试点成提交,懵逼的WA了三次。第二题跟 symmetric tree 那个很像。第三题跟前几周周赛的第四题很像。第四题他们说是线性筛法求素数。

链接:https://leetcode.com/contest/weekly-contest-113

【949】Largest Time for Given Digits(第一题 4分)

给了一个数组里面四个整数(0-9),返回这个数组能生成的最大时间表示 HH:MM。

题解:暴力生成所有的排列,然后判断是否符合时间的定义,然后用ret变量标记最大的字符串。(时间相关的类似题:lc 681)

 class Solution {
public:
string largestTimeFromDigits(vector<int>& A) {
sort(A.begin(), A.end());
if (A[] >= ) {return "";}
string ret = "";
do {
string str = string(, A[] + '') + string(, A[] + '') + ":" + string(, A[] + '') + string(, A[] + '');
if (isValid(str)) {
if (str > ret) {
ret = str;
}
}
} while(next_permutation(A.begin(), A.end()));
return ret;
}
bool isValid(string str) {
if (str[] > '') { return false;}
if (str[] == '' && str[] >= '') { return false; }
if (str[] >= '') { return false;}
return true;
}
};

【951】Flip Equivalent Binary Trees(第二题 5分)

For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.

A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations.

Write a function that determines whether two binary trees are flip equivalent.  The trees are given by root nodes root1 and root2.

题解:我先判断有没有根,有根但是值不相等的话,就返回false,递归判断 root1 的左儿子和 root2 的左儿子 以及 root1 的右儿子和 root2 的右儿子 是不是 FlipEqui,如果是直接返回yes。否则递归判断 root1 的右儿子和 root2 的左儿子 以及 root1 的左儿子和 root2 的右儿子 是不是 FlipEqui,是的话,返回yes。都不行就返回false。(类似题:lc 101)

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool flipEquiv(TreeNode* root1, TreeNode* root2) {
if (!root1 && !root2) {return true;}
if (!root1 || !root2) {return false;}
if (root1->val != root2->val) {return false;}
bool res1 = flipEquiv(root1->left, root2->left) && flipEquiv(root1->right, root2->right);
if (res1) {
return res1;
}
bool res2 = flipEquiv(root1->left, root2->right) && flipEquiv(root1->right, root2->left);
if (res2) {
return res2;
}
return false;
}
};

【950】Reveal Cards In Increasing Order(第三题 5分)

我们有一个 N 张的 unique 纸牌,我们希望得到一个序列,按照下面步骤操作之后,从这个序列弹出的序列是完全排好序的。

(1)弹出最上面一张纸牌 A1。

(2)如果 A1 下面有纸牌 A2,把 A2 放到这叠纸牌的最下方。

依次循环做(1)(2)操作。

Example 1:
Input: [17,13,11,2,3,5,7]
Output: [2,13,3,11,5,17,7]
Explanation:
We get the deck in the order [17,13,11,2,3,5,7] (this order doesn't matter), and reorder it.
After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.
We reveal 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13].
We reveal 3, and move 11 to the bottom. The deck is now [5,17,7,13,11].
We reveal 5, and move 17 to the bottom. The deck is now [7,13,11,17].
We reveal 7, and move 13 to the bottom. The deck is now [11,17,13].
We reveal 11, and move 17 to the bottom. The deck is now [13,17].
We reveal 13, and move 17 to the bottom. The deck is now [17].
We reveal 17.
Since all the cards revealed are in increasing order, the answer is correct.

题解:先把数组排序好了之后,从小到大依次隔空插入。

 class Solution {
public:
vector<int> deckRevealedIncreasing(vector<int>& deck) {
const int n = deck.size();
sort(deck.begin(), deck.end());
vector<int> ret(n, -);
int gap = , k = ;
while (k < n) {
for (int i = ; i < n; ++i) {
if (ret[i] != -) {continue;}
if (gap) {
ret[i] = deck[k];
++k;
gap = ;
if (k >= n) {break;}
} else {
if (ret[i] == -) {gap = ;}
}
}
}
return ret;
}
};

【952】Largest Component Size by Common Factor (第四题 8分)

Contest 114(2018年12月9日)(题号953-956)

比赛情况记录:本周一直比较萎靡,唉,结果:2/4,ranking: 696 / 3198,我认为第三题第四题都不难,然而实现上有困难,肯定是我的问题了。

链接:https://leetcode.com/contest/weekly-contest-114

【953】Verifying an Alien Dictionary(第一题 4分)

有一种外星文字也包含 'a’ 到 'z' 26个字母,只不过字母顺序不一样罢了。给了一堆 words,判断这些 words 是不是按照外星字典顺序排列的。

题解:我用 unordered_map 存储了外星字母对应英文字母的关系,然后把每一个 word 转换成英文单词,看这些单词是否符合字典顺序。

 class Solution {
public:
bool isAlienSorted(vector<string>& words, string order) {
//1. map relationship
unordered_map<char, char> mp;
for (int i = ; i < ; ++i) {
mp[order[i]] = i + 'a';
}
//2. change word
vector<string> inputs = words;
for (auto& w : inputs) {
for (auto& c : w) {
c = mp[c];
}
}
//3. check order
for (int i = ; i < inputs.size(); ++i) {
if (inputs[i] < inputs[i-]) {
return false;
}
}
return true;
}
};

【954】Array of Doubled Pairs(第二题 5分)

【955】Delete Columns to Make Sorted II(第三题 6分)(google tag)

给了一个字符串的数组,要求删除其中的几列,使得字符串数组字典序单调递增。返回需要删除的最小的列数。

Example 1:
Input: ["ca","bb","ac"]
Output: 1
Explanation:
After deleting the first column, A = ["a", "b", "c"].
Now A is in lexicographic order (ie. A[0] <= A[1] <= A[2]).
We require at least 1 deletion since initially A was not in lexicographic order, so the answer is 1. Example 2:
Input: ["xc","yb","za"]
Output: 0
Explanation:
A is already in lexicographic order, so we don't need to delete anything.
Note that the rows of A are not necessarily in lexicographic order:
ie. it is NOT necessarily true that (A[0][0] <= A[0][1] <= ...) Example 3:
Input: ["zyx","wvu","tsr"]
Output: 3
Explanation:
We have to delete every column. Note:
1 <= A.length <= 100
1 <= A[i].length <= 100

题解:我们可以有个很直观的想法,如果当前的这列加上去之后,会导致A[i] > A[i+1] 那么这列就可以删除了。我们可以设置一个空的字符串数组mat,代表A delete col之后的结果。依次遍历每一列,看要不要删除。如果删除,就res++,否则mat上加上这一列。

更进一步,我们可以用 vector<bool> sorted   来优化 mat 数组,sorted[i] = true 代表 A[i] < A[i+1] 已经严格小于了。这样我们检查下一列的时候就不需要考虑这两个字符串的大小关系可以直接跳过。

 class Solution {
public:
int minDeletionSize(vector<string>& A) {
const int n = A.size(), m = A[].size();
vector<bool> sorted(n, false);
int res();
for (int k = ; k < m; ++k) {
bool needDelete = false;
for (int i = ; i < n-; ++i) {
if (!sorted[i] && A[i][k] > A[i+][k]) {
res++; needDelete = true;
break;
}
}
if (needDelete) {continue;}
for (int i = ; i < n - ; ++i) {
if (!sorted[i] && A[i][k] < A[i+][k]) {
sorted[i] = true;
}
}
}
return res;
}
};

【956】Tallest Billboard(第四题 8分)

Contest 115(2018年12月16日)(题号957-960)

比赛情况记录:本周比赛马马虎虎吧,第四题不会做比较尴尬。结果: 2/4,ranking: 490/3055。第三题看了题真是没啥想法。第四题是个LIS的变种题(把一列看成一个元素,自己实现比较大小)。

链接:https://leetcode.com/contest/weekly-contest-115

【958】Check Completeness of a Binary Tree(第一题 5分)

检查一棵树是不是完全二叉树。

题解:第一题有稍微有点卡住了。有两种检测方法,都不是那么的直观。第一种是 dfs,判断是不是左右子树都是完全二叉树,然后判断左子树高度最多比右子树高度大一。第二种是 bfs,判断方法是

(1)如果当前结点有右孩子但是没有左孩子,那么直接返回false。

(2)如果当前结点不是左右孩子都有,那么后面的结点都必须是叶子结点。

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isCompleteTree(TreeNode* root) {
if (!root) {return true;}
queue<TreeNode*> que;
que.push(root);
bool mark = false;
while (!que.empty()) {
int size = que.size();
for (int i = ; i < size; ++i) {
TreeNode* cur = que.front(); que.pop();
if (mark && (cur->left || cur->right)) {
return false;
}
if (cur->left) {
que.push(cur->left);
}
if (cur->right) {
que.push(cur->right);
}
if (cur->left && !cur->right || !cur->left && !cur->right) {
mark = true;
}
if (cur->right && !cur->left) {
return false;
}
}
}
return true;
}
};

bfs

【957】Prison Cells After N Days(第二题 6分)

有一个数组里面有 8 个0/1元素, 分别代表8个囚室,0代表囚室为空,1代表囚室有人。每天囚室的人员分布都在变化。变化规则就是如下两条:

  • If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
  • Otherwise, it becomes vacant.

给了 Day 0 的囚室分布,问第 N 天的囚室分布。(1 <= N <= 10^9

题解:这题肯定是有循环节的。我们可以注意到第一个 cell 和最后一个 cell 肯定从第一天开始就都是 0 了,因为他们就没有两个邻居。然后中间的 6个 cell,它们要么是 0 要么是 1。所以循环节最多也就是 2^6 = 64 个排列。我们用个数组记录每个vector代表的二进制数。然后我们找循环节就行了。

 class Solution {
public:
vector<int> prisonAfterNDays(vector<int>& cells, int N) {
int number = vector2Int(cells);
vector<int> array(, -);
vector<int> nCells = cells;
int day = ;
do {
array[day++] = number;
number = transNextDay(nCells);
if (day == N + ) {
break;
}
} while (find(array.begin(), array.end(), number) == array.end());
if (day == N + ) {
vector<int> ret = getVector(array[N]);
return ret;
}
auto iter = find(array.begin(), array.end(), number);
const int startDay = distance(array.begin(), iter);
const int cycle = day - startDay;
int idx = ((N - startDay) % cycle);
vector<int> ret = getVector(array[startDay + idx]);
return ret;
}
int vector2Int(const vector<int>& nums) {
int pow = , ret = ;
for (int i = ; i < ; ++i) {
ret += pow * nums[i];
pow *= ;
}
return ret;
}
int transNextDay(vector<int>& nCells) {
vector<int> newCells(, );
for (int i = ; i < -; ++i) {
if (nCells[i-] ^ nCells[i+] == ) {
newCells[i] = ;
}
}
int ret = vector2Int(newCells);
nCells = newCells;
return ret;
}
vector<int> getVector(int num) {
vector<int> ret(, );
for (int i = ; i < ; ++i) {
ret[i] = num % ;
num /= ;
}
return ret;
}
};

【959】Regions Cut By Slashes(第三题 7分)

【960】Delete Columns to Make Sorted III(第四题 7分)

给了一个字符串数组 A,A[i] 表示一个字符串,我们要从字符矩阵A中删除某几列字符,使得每个字符串都是符合字母序的 (every element (row) in lexicographicorder)。问最少删除几列。

题解:这个题目有点像是 LIS,但是比赛的时候没想出来,我想的是每行都 LIS,然后求出 min(LIS) = x,在[1, x]中二分求最大的k。但是其实不是这样想的,这样暴力解复杂度太高,又难写。本题事实上应该把每一列都看成 LIS 的一个元素,然后我们自己定义元素的大小比较关系就行了。时间复杂度是 O(m*m*n)

 class Solution {
public:
int minDeletionSize(vector<string>& A) {
const int n = A.size(), m = A[].size();
vector<int> dp(m, );
int maxLen = ;
for (int i = m - ; i >= ; --i) {
for (int j = i + ; j < m; ++j) {
bool found = false;
for (int k = ; k < n; ++k) {
if (A[k][i] > A[k][j]) {
found = true;
break;
}
}
if (!found) {
dp[i] = max(dp[i], dp[j] + );
maxLen = max(maxLen, dp[i]);
}
}
}
return m - maxLen;
}
};

Contest 116(2018年12月23日)(题号961-964)

链接:https://leetcode.com/contest/weekly-contest-116

比赛情况记录:结果: 1/4,ranking: 1745/2965. 这两天我也不知道怎么了,锻炼练不下去,题目不想做,唉。希望只是一时状态不好而已。

【961】N-Repeated Element in Size 2N Array(第一题 2分)

【962】Maximum Width Ramp(第二题 5分)

给了一个数组 A,想找一对 tuple (i, j),满足 i < j && A[i] <= A[j]. 找到gap间距最大的 i, j, 返回 max(gap) 。

题解:看了lee215的解答,他说用 decreasing stack。其实我到现在都没有彻底get到这个点在哪里。吐血了。

 class Solution {
public:
int maxWidthRamp(vector<int>& A) {
const int n = A.size();
stack<int> stk;
for (int i = ; i < n; ++i) {
if (stk.empty() || A[stk.top()] > A[i]) {
stk.push(i);
}
}
int ret = ;
for (int i = n-; i > ; --i) {
while (!stk.empty() && A[i] >= A[stk.top()]) {
printf("i = %d, stk.top() = %d, A[i] = %d, A[stk.top()] = %d\n", i, stk.top(), A[i], A[stk.top()]);
ret = max(i - stk.top(), ret);
stk.pop();
}
}
return ret;
}
};

【963】Minimum Area Rectangle II(第三题 5分)

【964】Least Operators to Express Number (第四题 9分)

Contest 117(2018年12月30日)(题号965-968)

比赛情况记录:今天早上爬起来看群主mock interview,然后回去睡了一个回笼觉,结果就实在起不来了。所以这次是比赛之后马上开的virtual,virtual结果: 3/4,ranking:495/2770.

【965】Univalued Binary Tree(第一题 3分)

给了一棵二叉树判断整棵数是不是所有结点都是一个值。保证至少有一个根结点。

题解:dfs 或者 bfs 随你喜欢。

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isUnivalTree(TreeNode* root) {
if (!root) {return true;}
const int value = root->val;
queue<TreeNode*> que;
que.push(root);
bool ret = true;
while (!que.empty()) {
auto cur = que.front(); que.pop();
if (cur->val != value) {
ret = false;
break;
}
if (cur->left) {
que.push(cur->left);
}
if (cur->right) {
que.push(cur->right);
}
}
return ret;
} };

【967】Numbers With Same Consecutive Differences(第二题 5分)

返回所有长度为 N 的非负整数,相邻两个数位的差的绝对值是 K。前缀 0 的数是非法的,所以不要包含前缀 0 的数,比如 01,0 本身是合法的。

题解:dfs。我写的比较唠叨了,这题还可以更简洁。简洁版本有待补充。

 class Solution {
public:
vector<int> numsSameConsecDiff(int N, int K) {
vector<int> ret;
if (K == ) {
string strMul = string(N, '');
const int mul = stoi(strMul);
for (int i = ; i <= ; ++i) {
int number = i * mul;
ret.push_back(number);
}
if (N == ) {
ret.push_back();
}
return ret;
}
for (int i = ; i <= ; ++i) {
string strNum = to_string(i);
dfs(strNum, N - , K, ret);
}
if (N == ) {
ret.push_back();
}
return ret;
}
void dfs(string& strNum, int leftSize, const int K, vector<int>& ret) {
if (leftSize == ) {
ret.push_back(stoi(strNum));
return;
}
int back = strNum.back() - '';
if (back + K <= ) {
string strLastDigit = to_string(back + K);
string strNew = strNum + strLastDigit;
dfs(strNew, leftSize - , K, ret);
}
if (back - K >= ) {
string strLastDigit = to_string(back - K);
string strNew = strNum + strLastDigit;
dfs(strNew, leftSize - , K, ret);
}
return;
} };

【966】Vowel Spellchecker(第三题 6分)

给了一个单词表和一大堆 query,每次 query 给一个单词,问这个单词能不能通过给出的规则变成单词表里面的词。能的话,返回第一个单词表里面对应的单词。

规则一。query的单词本身就在单词表中。

规则二。query的单词通过更改大小写字母变换成单词表中单词。

规则三。query的单词通过更换元音字母变换成单词表中单词。(这个匹配大小写不敏感)

规则优先级按照一二三递减。

题解:我这题一开始超时了,后来翻了一下群记录,原来要把元音化成通配符,类似pattern那种感觉。

 class Solution {
public:
vector<string> spellchecker(vector<string>& wordlist, vector<string>& queries) {
set<string> stWord(wordlist.begin(), wordlist.end());
const int n = queries.size();
vector<string> ret(n, "");
set<char> stTemp = {'a', 'e', 'i', 'o', 'u'};
stVowel = stTemp;
//build map
for (int idx = ; idx < wordlist.size(); ++idx) {
string strNew = str2Lower(wordlist[idx]);
if (mp.find(strNew) == mp.end()) {
mp[strNew] = idx;
}
string s2 = str2Pattern(strNew);
if (mpVowels.find(s2) == mpVowels.end()) {
mpVowels[s2] = idx;
}
}
for (int i = ; i < n; ++i) {
string w = queries[i];
if (stWord.find(w) != stWord.end()) { //rule1
ret[i] = w;
} else if (mp.find(str2Lower(w)) != mp.end()) { //rule2
int idx = mp[str2Lower(w)];
ret[i] = wordlist[idx];
} else { //rule3
int idx = checkRule3(w);
if (idx == -) { continue; }
ret[i] = wordlist[idx];
}
}
return ret;
}
unordered_map<string, int> mp, mpVowels;
set<char> stVowel;
inline string str2Lower(string str) {
string strNew = str;
for (int i = ; i < strNew.size(); ++i) {
if (isupper(strNew[i])) {
strNew[i] = tolower(strNew[i]);
}
}
return strNew;
}
inline string str2Pattern(string str) {
string strNew = str;
for (auto & c: strNew) {
if (stVowel.find(c) != stVowel.end()) {
c = '*';
}
}
return strNew;
}
int checkRule3 (string str) {
string strNew = str2Lower(str);
strNew = str2Pattern(strNew);
int ret = -;
if (mpVowels.find(strNew) != mpVowels.end()) {
ret = mpVowels[strNew];
}
return ret;
}
};

【968】Binary Tree Cameras(第四题 8分)

Contest 118(2019年1月6日)(题号969-972)

链接:https://leetcode.com/contest/weekly-contest-118

总结:rank 730/3587, 结果:2/4。 具体比赛的时候的想法已经忘没了,尴尬。噢,第二题我本来是想出来的,结果手残了还没看出来。

【970】Powerful Integers(第一题 3分)

给了两个非负整数,x 和 y, 以及一个数 bound,求表达式 x^i + y^j 中所有小于等于 bound 的值,用数组的形式返回。其中 i >= 0, j >= 0。

题解:直接暴力,注意 x = 1 和 y = 1 的时候怎么办。不要写死循环了。

 class Solution {
public:
vector<int> powerfulIntegers(int x, int y, int bound) {
int curx = , cury = ;
set<int> ret;
for (int i = ; curx + cury <= bound; ++i) {
for (int j = ; curx + cury <= bound; ++j) {
if (curx + cury <= bound) {
ret.insert(curx + cury);
}
cury *= y;
if (cury * y == cury) {
break;
}
}
if (curx * x == curx) {
break;
}
curx *= x;
cury = ;
}
vector<int> ans;
for (auto s : ret) {
ans.push_back(s);
}
return ans;
}
};

【969】Pancake Sorting(第二题 5分)

煎饼排序,一次煎饼翻转的操作如下:我们可以选一个正整数 k,然后翻转前 k 个煎饼。输入是一个 A 数组,代表煎饼的大小,输出是一个 k 的数组,代表经过这个 k 数组的操作之后,A数组可以变成有序的。(k 的长度不超过 10 * A.size())

题解:我们可以考虑每次操作都使得一个煎饼放在最下方。可以这么操作,选出没有排序的数组中的最大煎饼,然后翻转一次,把最大的煎饼翻转到第一个位置,然后翻转整个没有排序的数组,把最大的煎饼从第一个位置换到最后一个位置。这样产生的 K 数组的大小是 2N。

 class Solution {
public:
vector<int> pancakeSort(vector<int>& A) {
vector<int> copyA(A), ret;
sort(copyA.begin(), copyA.end());
if (A == copyA) {
return ret;
}
n = A.size();
flip(A, ret, n, copyA);
// print(A);
return ret;
}
void flip(vector<int>& A, vector<int>& ret, int cur, const vector<int> sortedA) {
if (cur == ) {
return;
}
auto iter = find(A.begin(), A.end(), cur);
const int idx = distance(A.begin(), iter);
if (idx != ) {
reverse(A.begin(), iter + );
// print(A);
ret.push_back(idx + );
}
if (A == sortedA) {
return;
}
reverse(A.begin(), A.begin() + cur);
// print(A);
ret.push_back(cur);
if (A == sortedA) {
return;
}
flip(A, ret, cur-, sortedA);
}
void print(vector<int>& A) {
for (auto e : A) {
printf("%d ", e);
}
printf("\n");
}
int n;
};

【971】Flip Binary Tree To Match Preorder Traversal(第三题 6分)

【972】Equal Rational Numbers(第四题 8分)(第四题比赛的时候不会做,2019年1月17日算法群里的每日一题)

给了两个字符串 S 和 T,每个代表一个非负的有理数,如果他们相等的话,返回 True。有如下三种格式:

  • <IntegerPart> (e.g. 0, 12, 123)
  • <IntegerPart><.><NonRepeatingPart>  (e.g. 0.5, 1., 2.12, 2.0001)
  • <IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)> (e.g. 0.1(6), 0.9(9), 0.00(1212))
Example 1:
Input: S = "0.(52)", T = "0.5(25)"
Output: true
Explanation:
Because "0.(52)" represents 0.52525252..., and "0.5(25)" represents 0.52525252525..... , the strings represent the same number. Example 2:
Input: S = "0.1666(6)", T = "0.166(66)"
Output: true Example 3:
Input: S = "0.9(9)", T = "1."
Output: true
Explanation:
"0.9(9)" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.]
"1." represents the number 1, which is formed correctly: (IntegerPart) = "1" and (NonRepeatingPart) = ""

数据规模:

  1. Each part consists only of digits.
  2. The <IntegerPart> will not begin with 2 or more zeros.  (There is no other restriction on the digits of each part.)
  3. 1 <= <IntegerPart>.length <= 4
  4. 0 <= <NonRepeatingPart>.length <= 4
  5. 1 <= <RepeatingPart>.length <= 4

题解:我们可以考虑把整个字符串转换成double,如果没有循环节的话直接调用库函数 stod,如果有循环节的话,扩展一下循环节。因为循环节的长度最长也才4位,它可能有 1,2, 3, 4 这么长,所以我们可以拓展循环节到12位长度,这样不管它是1,2,3,4最后两个数都能拓展成一样的。

 class Solution {
public:
bool isRationalEqual(string S, string T) {
return abs(StrToDouble(S) - StrToDouble(T)) < 1e-;
}
double StrToDouble(string s) {
auto pos = s.find('(');
if (pos == string::npos) {
return stod(s);
}
string base = s.substr(, pos), repeat = s.substr(pos + , s.size() - - pos - );
while (base.size() < ) {
base += repeat;
}
return stod(base);
}
};

Contest 119(2019年1月13日)(题号973-976)

链接:https://leetcode.com/contest/weekly-contest-119

总结:3/4,rank:1024/3847 第二题超时了好几次,第三题有个负数没有考虑。第三题也想了挺久的。orz

【973】K Closest Points to Origin(第一题 3分)

给了一堆坐标,返回离原点最近的 K 个坐标。

题解:直接排序,返回前 K 个。

 class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
const int n = points.size();
if (n <= K) {
return points;
}
vector<pair<int, vector<int>>> dis(n);
for (int i = ; i < n; ++i) {
auto p = points[i];
int d = p[] * p[] + p[] * p[];
dis[i] = make_pair(d, p);
}
sort(dis.begin(), dis.end());
vector<vector<int>> ans(K);
for (int i = ; i < K; ++i) {
ans[i] = dis[i].second;
}
return ans;
}
};

【976】Largest Perimeter Triangle(第二题 4分)

给了一个数组 A 代表边长,求能组成周长最长的三角形的周长。

数据规模:

  1. 3 <= A.length <= 10000
  2. 1 <= A[i] <= 10^6

题解:先排序,从大到小排序。第一个能组成的三角形就是所求的,而且这三个边长的变量元素一定是相邻的三个元素。想象一下如果相邻的第三个元素不能和前两个元素组成三角形,那么后面的元素肯定小于等于第三个元素,更加不能组成三角形。

 class Solution {
public:
int largestPerimeter(vector<int>& A) {
const int n = A.size();
sort(A.begin(), A.end(), cmp);
int ans = ;
for (int i = ; i < n - ; ++i) {
int l1 = A[i], l2 = A[i+], l3 = A[i+];
if (l2 + l3 <= l1) {continue;}
if (l1 - l2 >= l3 || l1 - l3 >= l2 || l2 - l3 >= l1) {continue;}
ans = l1 + l2 + l3;
if (ans > ) {
return ans;
}
}
return ans;
}
static bool cmp(const int& a, const int& b) {
return a > b;
}
};

【974】Subarray Sums Divisible by K(第三题 6分)

【975】Odd Even Jump(第四题 8分)

Contest 120(2019年1月20日)(题号977-980)

结果:3/4,rank:557 / 3876。做了第一题,第二题,第四题,第三题差点就做出来了,orz。

链接:https://leetcode.com/contest/weekly-contest-120

【977】Squares of a Sorted Array(第一题 2分)

给了一个排序数组,里面有正有负,返回这个数组的平方数组,需要排序排好。

Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]

题解:我是先用了一个 lower_bound 找到了 0  的位置,然后 2 pointers,一个指向正数往大了走,一个指向负数往小了走。

 class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
const int n = A.size();
auto iter = lower_bound(A.begin(), A.end(), );
vector<int> ret(n);
if (iter == A.begin() || iter == A.end()) {
for (int i = ; i < n; ++i) {
ret[i] = A[i] * A[i];
}
if (iter == A.end()) {
reverse(ret.begin(), ret.end());
}
} else {
int p1 = distance(A.begin(), iter), p2 = p1 - ; //++p1, --p2
int cnt = ;
while (p1 < n && p2 >= ) {
if (abs(A[p2]) < abs(A[p1])) {
ret[cnt++] = A[p2] * A[p2];
--p2;
} else {
ret[cnt++] = A[p1] * A[p1];
++p1;
}
}
while (p1 < n) {
ret[cnt++] = A[p1] * A[p1];
++p1;
}
while (p2 >= ) {
ret[cnt++] = A[p2] * A[p2];
--p2;
}
}
return ret;
}
};

【978】Longest Turbulent Subarray(第二题 5分)

找出最长的连续子数组,子数组中的元素满足如下性质之一,

  • For i <= k < jA[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even;
  • OR, for i <= k < jA[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd.

返回最长子数组的长度。

题解:我们求原数组的差分数组,diff[i] = A[i]-A[i-1], 然后只保留正负号(正数是1,负数是-1)。我们用dp求最长的连续子数组,dp[i] 代表以 i 为结尾的 diff 数组的最长的连续正负子序列的长度。

if (diff[i] * diff[i-] == -) {
dp[i] = dp[i-]+;
} else {
dp[i] = ;
}
 class Solution {
public:
int maxTurbulenceSize(vector<int>& A) {
const int n = A.size();
if (n <= ) {
return n;
}
vector<int> diff(n, );
for (int i = ; i < n; ++i) {
diff[i] = A[i] - A[i-];
if (diff[i] < ) {
diff[i] = -;
} else if (diff[i] > ) {
diff[i] = ;
}
}
// vector<int> dp(n, 1);
// dp[0] = 0;
int cur = , pre = ;
int ret = ;
for (int i = ; i < n; ++i) {
if (diff[i] * diff[i-] == -) {
//dp[i] = dp[i-1] + 1;
cur = pre + ;
ret = max(ret, cur);
} else {
cur = ;
}
pre = cur;
}
return ret + ;
}
};

【979】Distribute Coins in Binary Tree(第三题 6分)

给了一棵二叉树,上面有 N 个节点,N 个节点上面有 N 个coin,我们把 一个节点上的一个硬币移动到它的儿子节点或者父节点,称为一个 move,问把 N 个节点上每个节点上都有一个 coin,问需要多少步数。

题解:我比赛的时候先序遍历,中序遍历都想了,就是没想后序遍历,后来想到了,结果就差一点点ac了,尴尬。

我们可以这么思考,如果一个节点是叶子节点,它上面有三个硬币,那么它可以自己留一个,上交给爸爸两个,返回2。如果它上面有1个硬币,它就可以自己留着一个,不上交爸爸,返回0。如果它上面没有硬币,它就可以找它爸爸要一个,返回-1。

爸爸接到了儿子的信息,它要修改下自己的数量。儿子上交了,它就加上,儿子找它要,它就先给它儿子。然后我们用每次要的数量的绝对值累加步数。dfs一下,结果就呼之欲出了。

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int moves = ;
int distributeCoins(TreeNode* root) {
if (!root) { return ; }
dfs(root);
return moves;
}
int dfs(TreeNode* root) { //return states: 0->no need, -3->need 3 coins, +3->give 3 coins
if (!root) {return ;}
if (!root->left && !root->right) {
return root->val - ;
}
int l = dfs(root->left);
root->val += l;
moves += abs(l);
int r = dfs(root->right);
root->val += r;
moves += abs(r);
return root->val - ;
}
};

【980】Unique Paths III(第四题 7分)

给了一个2D grid,上面 1 代表起点,2代表重点,0代表可以走的路,-1代表障碍。题目要求我们从起点开始,遍历过所有能走的路,走到终点。求一共有多少中走法。

  1. 1 <= grid.length * grid[0].length <= 20

题解:我直接dfs了,数据规模很小。此外本题还可以状压dp,昨天被旅行商问题搞出了心理阴影,所以,今天先不想状压dp了。orz

 class Solution {
public:
int visTot = , obs = ;
int n, m, total;
int ret = ;
vector<int> begin{-, -}, end{-, -};
vector<int> dirx = {-, , , };
vector<int> diry = {, -, , };
int uniquePathsIII(vector<vector<int>>& grid) {
n = grid.size(), m = grid[].size();
for (int i = ; i < n; ++i) {
for (int j = ; j < m; ++j) {
if (grid[i][j] == ) {
begin = {i, j};
} else if (grid[i][j] == ) {
end = {i, j};
} else if (grid[i][j] == -) {
obs++;
}
}
}
total = n * m - obs;
vector<vector<int>> visit = grid;
dfs(grid, visit, begin[], begin[]);
return ret;
}
void dfs(const vector<vector<int>>& grid, vector<vector<int>>& visit, int curx, int cury) {
if (curx == end[] && cury == end[] && visTot + == total) {
++ret;
}
visit[curx][cury] = ;
visTot++;
for (int i = ; i < ; ++i) {
int newx = curx + dirx[i], newy = cury + diry[i];
if (newx >= && newx < n && newy >= && newy < m && visit[newx][newy] != - && visit[newx][newy] != ) {
dfs(grid, visit, newx, newy);
}
}
visit[curx][cury] = ;
visTot--;
}
};




【Leetcode周赛】从contest-111开始。(一般是10个contest写一篇文章)的更多相关文章

  1. 【Leetcode周赛】从contest-91开始。(一般是10个contest写一篇文章)

    Contest 91 (2018年10月24日,周三) 链接:https://leetcode.com/contest/weekly-contest-91/ 模拟比赛情况记录:第一题柠檬摊的那题6分钟 ...

  2. 【Leetcode周赛】从contest1开始。(一般是10个contest写一篇文章)

    注意,以前的比赛我是自己开了 virtual contest.这个阶段的目标是加快手速,思考问题的能力和 bug-free 的能力. 前面已经有了100个contest.计划是每周做三个到五个cont ...

  3. 【Leetcode周赛】从contest-41开始。(一般是10个contest写一篇文章)

    Contest 41 ()(题号) Contest 42 ()(题号) Contest 43 ()(题号) Contest 44 (2018年12月6日,周四上午)(题号653—656) 链接:htt ...

  4. 【Leetcode周赛】从contest-51开始。(一般是10个contest写一篇文章)

    Contest 51 (2018年11月22日,周四早上)(题号681-684) 链接:https://leetcode.com/contest/leetcode-weekly-contest-51 ...

  5. 【Leetcode周赛】从contest-71开始。(一般是10个contest写一篇文章)

    Contest 71 () Contest 72 () Contest 73 (2019年1月30日模拟) 链接:https://leetcode.com/contest/weekly-contest ...

  6. 【Leetcode周赛】从contest-81开始。(一般是10个contest写一篇文章)

    Contest 81 (2018年11月8日,周四,凌晨) 链接:https://leetcode.com/contest/weekly-contest-81 比赛情况记录:结果:3/4, ranki ...

  7. 【Leetcode周赛】从contest-121开始。(一般是10个contest写一篇文章)

    Contest 121 (题号981-984)(2019年1月27日) 链接:https://leetcode.com/contest/weekly-contest-121 总结:2019年2月22日 ...

  8. 【LeetCode】从contest-21开始。(一般是10个contest写一篇文章)

    [LeetCode Weekly Contest 29][2017/04/23] 第17周 Binary Tree Tilt (3) Array Partition I (6) Longest Lin ...

  9. 【Leetcode周赛】比赛目录索引

    contest 1 ~ contest 10: contest 11 ~ contest 20: contest 21 ~ contest 30 : https://www.cnblogs.com/z ...

随机推荐

  1. laravel后台账户登录验证(5.5.48版本)

    首先我是菜鸟,对laravel框架也不是很熟悉,突然有一天心血来潮就想研究一下laravel的后台登录用户登录的流程, 虽然公司项目中有这样的一套流程,也看了好几遍,越看越简单,越看我就越会了,当自己 ...

  2. js点击获取—通过JS获取图片的绝对对坐标位置

    一.通过JS获取鼠标点击时图片的相对坐标位置 源代码如下所示:  <!DOCTYPE html> <html lang="en"> <head> ...

  3. 20180805-Java ByteArrayInputStream类

    ByteArrayInputStream bArray = new ByteArrayInputStream(byte [] a); ByteArrayInputStream bArray = new ...

  4. SqlServer 查看缓存 并合理设置最大内存

    SqlServer 服务器运行一段时间发现内存逐渐增长 飙升到98%了 解决方法: 重启主机 重启SqlServer服务 设置最大内存 前两种方法不太适合线上环境 且指标不治本 建议用设置最大内存 如 ...

  5. grammar_action

    w ll = [] for i in range(0, 10, 1): ll.append(i) print(ll) for i in ll: if i < 6: print(i) index_ ...

  6. MySQL 中的 information_schema 数据库

    1. 概述 information_schema 数据库跟 performance_schema 一样,都是 MySQL 自带的信息数据库.其中 performance_schema 用于性能分析,而 ...

  7. Centos安装GD库

    tar zxvf ncurses-5.6.tar.gz 进入目录 cd ncurses-5.6 生成 makefile文件,再进一步编译 ./configure --prefix=/usr --wit ...

  8. Altium Designer chapter2总结

    原理图开发环境这节中需要注意的如下: (1)电路图首先项设定中需注意的地方: 1.General:中经常用到的自动生成交叉节点.放置元件时自动增加选项.复合封装元件的字母数字后缀选项.默认电源对象名称 ...

  9. pygame应用——生产者消费者模型

    因为操作系统的一个生产者-消费者拓展作业,以一个飞机大战的模型修改来的 import pygame import time from pygame.locals import * bulletsNum ...

  10. jdk (Java Development Kit)

    JDK是 Java 语言的软件开发工具包,主要用于移动设备.嵌入式设备上的java应用程序.JDK是整个java开发的核心,它包含了JAVA的运行环境(JVM+Java系统类库)和JAVA工具. JD ...