【334】Increasing Triplet Subsequence (2019年2月14日,google tag)(greedy)

给了一个数组 nums,判断是否有三个数字组成子序列,使得子序列递增。题目要求time complexity: O(N),space complexity: O(1)

Return true if there exists i, j, k 
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.

题解:可以dp做,LIS 最少 nlog(n)。 这个题可以greedy,可以做到O(N). 我们用两个变量,min1 表示当前最小的元素,min2表示当前第二小的元素。可以分成三种情况讨论:

(1)nums[i] < min1, -> min1 = nums[i]

(2)nums[i] > min1 && nums[i] < min2 -> min2 = nums[i]

(3)nums[i] > min2 -> return true

 class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int min1 = INT_MAX, min2 = INT_MAX;
for (auto& num : nums) {
if (num > min2) {return true;}
else if (num < min1) {
min1 = num;
} else if (min1 < num && num < min2) {
min2 = num;
}
}
return false;
}
};

【388】Longest Absolute File Path (2019年3月13日) (google tag,没分类)

给了一个string代表一个文件目录的层级。

The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents:

dir
subdir1
file1.ext
subsubdir1
subdir2
subsubdir2
file2.ext

返回一个文件的绝对路径最长的长度,文件层级之间用slash分割。

Note:

  • The name of a file contains at least a . and an extension.
  • The name of a directory or sub-directory will not contain a ..

Time complexity required: O(n) where n is the size of the input string.

Notice that a/aa/aaa/file1.txt is not the longest file path, if there is another path aaaaaaaaaaaaaaaaaaaaa/sth.png.

题解:题目要求用O(N)的解法。看清题意,用tab表示当前的层级。一行一行处理,用'\n'分割行,用'\t'的个数来决定层级。

 class Solution {
public:
int lengthLongestPath(string input) {
const int n = input.size();
vector<int> stk; //
int start = , end = ;
int res = ;
while (end < n) { //这个while循环处理一行
int level = ;
if (input[end] == '\t') { //处理前面的 /t 的个数,决定当前的层级
while (end < n && input[end] == '\t') { ++level; ++end;}
}
while (stk.size() > level) { stk.pop_back(); }
string word = "";
while (end < n && input[end] != '\n') { //归档当前的文件夹的名称,和文件名称
word += input[end];
++end;
}
int temp = word.size() + (stk.empty() ? : stk.back()) + ;
stk.push_back(temp);
if (temp > res) {
int p = word.find('.');
if (p != string::npos && p < word.size() - ) {
res = temp;
}
}
if (end < n && input[end] == '\n') {++end;}
}
return res == ? res : res - ;
}
};

【419】Battleships in a Board (2018年11月25日)(谷歌的题,没分类。)

给了一个二维平面,上面有 X 和 . 两种字符。 一行或者一列连续的 X 代表一个战舰,问图中有多少个战舰。(题目要求one pass, 空间复杂度是常数)

题目说了每两个战舰之间起码有一个 . 作为分隔符,所以不存在正好交叉的情况。

题解:我提交了一个 floodfill 的题解,能过但是显然不满足要求。

discuss里面说,我们可以统计战舰的最上方和最左方,从而来统计战舰的个数。(这个解法是满足要求的。)

 class Solution {
public:
int countBattleships(vector<vector<char>>& board) {
n = board.size();
m = board[].size();
int ret = ;
for (int i = ; i < n; ++i) {
for (int j = ; j < m; ++j) {
if (board[i][j] == '.') {continue;}
if ((i == || board[i-][j] != 'X') && (j == || board[i][j-] != 'X')) {ret++;}
}
}
return ret;
}
int n, m;
};

【427】Construct Quad Tree(2019年2月12日)

建立四叉树。https://leetcode.com/problems/construct-quad-tree/description/

题解:递归

 /*
// Definition for a QuadTree node.
class Node {
public:
bool val;
bool isLeaf;
Node* topLeft;
Node* topRight;
Node* bottomLeft;
Node* bottomRight; Node() {} Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
val = _val;
isLeaf = _isLeaf;
topLeft = _topLeft;
topRight = _topRight;
bottomLeft = _bottomLeft;
bottomRight = _bottomRight;
}
};
*/
class Solution {
public:
Node* construct(vector<vector<int>>& grid) {
const int n = grid.size();
vector<int> tl = {, }, br = {n-, n-};
return construct(grid, tl, br);
}
Node* construct(vector<vector<int>>& grid, vector<int> tl, vector<int> br) {
if (tl == br) {
Node* root = new Node(grid[tl[]][tl[]], true, nullptr, nullptr, nullptr, nullptr);
return root;
}
int t = tl[], b = br[], l = tl[], r = br[];
bool split = false;
for (int i = t; i <= b; ++i) {
for (int j = l; j <= r; ++j) {
if (grid[i][j] != grid[t][l]) {
split = true;
}
}
}
if (!split) {
Node* root = new Node(grid[tl[]][tl[]], true, nullptr, nullptr, nullptr, nullptr);
return root;
}
Node* root = new Node(, false, nullptr, nullptr, nullptr, nullptr);
int newx = (t + b) / , newy = (l + r) / ;
root->topLeft = construct(grid, tl, {newx, newy});
root->topRight = construct(grid, {t, newy+}, {newx, r});
root->bottomLeft = construct(grid, {newx + , l}, {b, newy});
root->bottomRight = construct(grid, {newx+, newy+}, br);
return root;
}
};

【433】 Minimum Genetic Mutation(2018年12月28日,周五)(谷歌的题,没分类)

给了两个字符串基因序列start 和 end,和一个 word bank,每次操作需要把当前序列,通过一次变异转换成word bank里面的另外一个词,问从 start 转换成 end,至少需要几步?

题解:问最少几步,直接bfs解

 class Solution {
public:
int minMutation(string start, string end, vector<string>& bank) {
const int n = bank.size();
vector<int> visit(n, );
queue<string> que;
que.push(start);
int step = ;
int ret = -;
while (!que.empty()) {
step++;
const int size = que.size();
for (int i = ; i < size; ++i) {
string cur = que.front(); que.pop();
for (int k = ; k < n; ++k) {
if (visit[k]) {continue;}
if (diff(bank[k], cur) == ) {
visit[k] = ;
que.push(bank[k]);
if (bank[k] == end) {
ret = step;
return ret;
}
}
}
}
}
return ret;
}
int diff (string s1, string s2) {
if (s1.size() != s2.size()) {return -;}
int cnt = ;
for (int i = ; i < s1.size(); ++i) {
if (s1[i] != s2[i]) {
++cnt;
}
}
return cnt;
}
};

【481】 Magical String (2019年3月28日)(google tag)

给定一个string,S = "1221121221221121122……",生成规则是

If we group the consecutive '1's and '2's in S, it will be:

1 22 11 2 1 22 1 22 11 2 11 22 ......

and the occurrences of '1's or '2's in each group are:

1 2 2 1 1 2 1 2 2 1 2 2 ......

You can see that the occurrence sequence above is the S itself.

题目的问题是:给定一个数字 n,代表 s 的长度,问在长度为 n 的 s 中,有多少个 1。

题解:其实这道题可以归类为 2 pointers,我们想象一下,fast 可以每次走一步或者走两步,slow 每次走一步,slow 每次走一步,它指向的数字,就代表fast每次要走一步还是走两步。

比如一开始 s = "122", slow = 2 (代表 slow 指向 index = 2 的位置)这个时候,我们需要在 s 的末尾增加两个数字,增加2还是1呢,需要和当前 s 的末尾不相同就可以了。

这样的话,我们就能生成长度为 n 的 s 序列,然后数一下里面有多少个 1 就可以了。

 class Solution {
public:
int magicalString(int n) {
if (n == ) {return ;}
string s = "";
int idx = , res = ;
while (s.size() < n) {
char c = '' - s.back() + '';
if (s[idx] == '') {
s.push_back(c);
if (s.size() <= n && c == '') {++res;}
} else {
s.push_back(c);
if (s.size() <= n && c == '') {++res;}
s.push_back(c);
if (s.size() <= n && c == '') {++res;}
}
++idx;
}
return res;
}
};

【504】Base 7 (2018年11月25日)

Given an integer, return its base 7 string representation.

Example :
Input:
Output: "" Example :
Input: -
Output: "-10"

Note: The input will be in range of [-1e7, 1e7].

题解:直接按照进制转换

 class Solution {
public:
string convertToBase7(int num) {
bool negative = false;
if (num < ) {
negative = true;
num = -num;
}
string ret = "";
while (num != ) {
int mod = num % ;
num = num / ;
ret = to_string(mod) + ret;
}
ret = negative ? "-" + ret : ret;
ret = ret == "" ? "" : ret;
return ret;
}
};

【506】Relative Ranks(2018年11月25日)

Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".

Example :
Input: [, , , , ]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "", ""]
Explanation: The first three athletes got the top three highest scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal".
For the left two athletes, you just need to output their relative ranks according to their scores.

Note:

  1. N is a positive integer and won't exceed 10,000.
  2. All the scores of athletes are guaranteed to be unique.
 class Solution {
public:
vector<string> findRelativeRanks(vector<int>& nums) {
const int n = nums.size();
map<int, int, greater<int>> mp;
for (int i = ; i < nums.size(); ++i) {
int score = nums[i];
mp[score] = i;
}
vector<string> ret(n);
int cnt = ;
for (auto e : mp) {
int idx = e.second;
if (cnt <= ) {
if (cnt == ) {
ret[idx] = "Gold Medal";
}
if (cnt == ) {
ret[idx] = "Silver Medal";
}
if (cnt == ) {
ret[idx] = "Bronze Medal";
}
++cnt;
} else {
ret[idx] = to_string(cnt++);
}
}
return ret;
}
};

【540】Single Element in a Sorted Array(2018年12月8日,本题不是自己想的,看了花花酱的视频,需要review)

给了一个有序数组,除了一个数字外,其他所有数字都出现两次。用 O(logN) 的时间复杂度,O(1) 的空间复杂度把只出现一次的那个数字找出来。

题解:二分。怎么二分。我们的目的的找到第一个不等于它partner的数字。如何定义一个数的 partner,如果 i 是偶数,那么 nums[i] 的partner是 nums[i+1]。如果 i 是奇数,nums[i] 的partner 是 i-1。

 class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
const int n = nums.size();
int left = , right = n;
while (left < right) {
int mid = (left + right) / ;
int partner = mid % == ? mid + : mid - ;
if (nums[mid] == nums[partner]) {
left = mid + ;
} else {
right = mid;
}
}
return nums[left];
}
};

【797】All Paths From Source to Target (2018年11月27日)

给了一个 N 个结点的 DAG,结点标号是0 ~ N-1,找到从 node 0 到 node N-1 的所有路径,并且返回。

Example:
Input: [[1,2], [3], [3], []]
Output: [[0,1,3],[0,2,3]]
Explanation: The graph looks like this:
0--->1
| |
v v
2--->3
There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.

题解:dfs可以解。

 class Solution {
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
n = graph.size();
vector<vector<int>> paths;
vector<int> path(, );
dfs(graph, paths, path);
return paths;
}
void dfs(const vector<vector<int>>& graph, vector<vector<int>>& paths, vector<int>& path) {
if (path.back() == n-) {
paths.push_back(path);
return;
}
int node = path.back();
for (auto adj : graph[node]) {
path.push_back(adj);
dfs(graph, paths, path);
path.pop_back();
}
}
int n;
};


【LeetCode】未分类(tag里面没有)(共题)的更多相关文章

  1. 【LeetCode】按 tag 分类索引 (900题以下)

    链表:https://www.cnblogs.com/zhangwanying/p/9797184.html (共34题) 数组:https://www.cnblogs.com/zhangwanyin ...

  2. [LeetCode] All questions numbers conclusion 所有题目题号

    Note: 后面数字n表明刷的第n + 1遍, 如果题目有**, 表明有待总结 Conclusion questions: [LeetCode] questions conclustion_BFS, ...

  3. 【LeetCode】链表 linked list(共34题)

    [2]Add Two Numbers (2018年11月30日,第一次review,ko) 两个链表,代表两个整数的逆序,返回一个链表,代表两个整数相加和的逆序. Example: Input: ( ...

  4. 【LeetCode】线段树 segment-tree(共9题)+ 树状数组 binary-indexed-tree(共5题)

    第一部分---线段树:https://leetcode.com/tag/segment-tree/ [218]The Skyline Problem [307]Range Sum Query - Mu ...

  5. 【LeetCode】前缀树 trie(共14题)

    [208]Implement Trie (Prefix Tree) (2018年11月27日) 实现基本的 trie 树,包括 insert, search, startWith 操作等 api. 题 ...

  6. 【LeetCode】回溯法 backtracking(共39题)

    [10]Regular Expression Matching [17]Letter Combinations of a Phone Number [22]Generate Parentheses ( ...

  7. 【LeetCode】深搜DFS(共85题)

    [98]Validate Binary Search Tree [99]Recover Binary Search Tree [100]Same Tree [101]Symmetric Tree [1 ...

  8. 【LeetCode】随机化算法 random(共6题)

    [384]Shuffle an Array(2019年3月12日) Shuffle a set of numbers without duplicates. 实现一个类,里面有两个 api,struc ...

  9. 【LeetCode】拓扑排序 topological-sort(共5题)

    [207]Course Schedule [210]Course Schedule II [269]Alien Dictionary [329]Longest Increasing Path in a ...

随机推荐

  1. AT2371 Placing Squares

    题解 考虑\(dp\) \[ dp[i]=\sum_{i=0}^{i-1}dp[j]*(i-j)^2 \] 我们可以设\((i-j)\)为\(x\),那么随着\(i\)向右移动一格,每个\(x\)都是 ...

  2. vue中动态加载图片路径的方法

    assets:在项目编译的过程中会被webpack处理解析为模块依赖,只支持相对路径的形式,如< img src=”./logo.png”>和background:url(./logo.p ...

  3. ORA-20011

    Sun Jul 23 22:09:07 2017DBMS_STATS: GATHER_STATS_JOB encountered errors. Check the trace file.Errors ...

  4. 状压dp(8.8上午)

    神马是状态压缩? 就是当普通dp的每一维表示的状态非常少的时候,可以压缩成一维来表示 如果m==8 dp[i][0/1][0/1]......[0/1] 压缩一下 dp[i][s]表示到了第i行,状态 ...

  5. 二十六、python中json学习

    1.json序列介绍:提供4个关键字:dumps,dump,loads,load(与pickle用法完全相同) 语法:f.write(bytes(json.dumps(dict),encoding=& ...

  6. BeautifulSoup模块学习文档

    一.BeautifulSoup简介 1.BeautifulSoup模块 Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档 ...

  7. Jmeter之Switch Controller

    在测试过程中,各种不同的情况需要执行不同的操作,这个时候用if控制器比较麻烦,此时就可以使用Switch Controller代替. 一.界面显示 二.配置说明 1.名称:标识 2.注释:备注 3.S ...

  8. Navicat Premium for Mac 非官方版不能启动的解决方案

    Ps:这篇有点杂记的感觉,就说点废话也没什么影响.废话主要有两点: 1.建议读者也开始写博客,为什么呢?其实我也没有这种写作的习惯,我最开始写博客的时候,感觉我写的东西网上都有,需要的时候找一下肯定能 ...

  9. windows 10上玩耍ubuntu

    win10 已经支持运行子系统ubuntu了. 安装ubuntu 程序和功能>>启用或关闭Windows功能>>勾选"适用于Linux的Windows子系统" ...

  10. [Udemy] ES 7 and Elastic Stack - part 2

    Section 3: Searching with Elasticsearch query with json 分页返回 Sort full text 的内容不能用来sort, 比如movie的 ti ...