【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. [CF1093E]Intersection of Permutations:树套树+pbds

    分析 裸的二维数点,博主用树状数组套平衡树写的,顺便pbds真好用. Update on 2018/12/20:再解释一下为什么是二维数点,第一维是\(la \leq i \leq ra\),第二维是 ...

  2. Build安装版的UE4

    在项目中自己编译的引擎分发给团队可以参考以下两个链接 http://jackknobel.com/BuildGraph/Building-an-installed-ue4/ https://docs. ...

  3. 学习C#20天有感

    自学C#有20多天了,期间出差去深圳一周,每天平均学习4小时左右,看书+视频,之前有点C语言基础(仅限于基础哈哈),计划30内把C#的基本语法和SQL的基本语法熟悉,把面向对象相对深入的理解一些,然后 ...

  4. centos6.X mysql 5.1 主主配置

    1.配置文件 A库的配置文件: 在 /etc/my.cnf [mysqld] 段 新增: server_id= # log_bin 日志路径.格式以及删除时间(30天) log_bin=/var/li ...

  5. 阶段1 语言基础+高级_1-3-Java语言高级_1-常用API_1_第2节 匿名对象_6-匿名对象的说明

    没有名字的对象,叫做匿名对象 新建一个Person类 把赵又廷赋值交给匿名对象Person里面的成员变量name 想调用里面的ShowName的话 还需要再定义一个匿名对象. 第三个对象是一个全新的. ...

  6. python 每周作业

    day2:python的简介与认识day2:# 1.写一个登录程序# username# passwd# 让用户输入账号和密码,输入用户和密码输入正确的话# 提示你 xxx,欢迎登录,今天的日期是xx ...

  7. set()运算

    1 计算两个list的关系时,可转化为set进行运算. 参考:https://www.runoob.com/python3/python3-set.html a =[1,4,3,5,6,6,7,7,7 ...

  8. python正则表达式整理

    正则表达式在处理字符串时很大的作用,爬虫中也经常用到,下面就将一些常用正则表达式做一整理记录,方便以后查看. ^d   表示匹配以d开头的字符串 .      表示匹配任意字符串 *     表示前面 ...

  9. 【BASIS系列】SAP /usr/sap//DVEBMGS00满了怎么处理

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[BASIS系列]SAP /usr/sap//D ...

  10. <编译原理 - 函数绘图语言解释器(3)解释器 - python>

    <编译原理 - 函数绘图语言解释器(3)解释器 - python> <编译原理 - 函数绘图语言解释器(2)词法分析器 - python> <编译原理 - 函数绘图语言解 ...