【LeetCode】未分类(tag里面没有)(共题)
【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:
- N is a positive integer and won't exceed 10,000.
- 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里面没有)(共题)的更多相关文章
- 【LeetCode】按 tag 分类索引 (900题以下)
链表:https://www.cnblogs.com/zhangwanying/p/9797184.html (共34题) 数组:https://www.cnblogs.com/zhangwanyin ...
- [LeetCode] All questions numbers conclusion 所有题目题号
Note: 后面数字n表明刷的第n + 1遍, 如果题目有**, 表明有待总结 Conclusion questions: [LeetCode] questions conclustion_BFS, ...
- 【LeetCode】链表 linked list(共34题)
[2]Add Two Numbers (2018年11月30日,第一次review,ko) 两个链表,代表两个整数的逆序,返回一个链表,代表两个整数相加和的逆序. Example: Input: ( ...
- 【LeetCode】线段树 segment-tree(共9题)+ 树状数组 binary-indexed-tree(共5题)
第一部分---线段树:https://leetcode.com/tag/segment-tree/ [218]The Skyline Problem [307]Range Sum Query - Mu ...
- 【LeetCode】前缀树 trie(共14题)
[208]Implement Trie (Prefix Tree) (2018年11月27日) 实现基本的 trie 树,包括 insert, search, startWith 操作等 api. 题 ...
- 【LeetCode】回溯法 backtracking(共39题)
[10]Regular Expression Matching [17]Letter Combinations of a Phone Number [22]Generate Parentheses ( ...
- 【LeetCode】深搜DFS(共85题)
[98]Validate Binary Search Tree [99]Recover Binary Search Tree [100]Same Tree [101]Symmetric Tree [1 ...
- 【LeetCode】随机化算法 random(共6题)
[384]Shuffle an Array(2019年3月12日) Shuffle a set of numbers without duplicates. 实现一个类,里面有两个 api,struc ...
- 【LeetCode】拓扑排序 topological-sort(共5题)
[207]Course Schedule [210]Course Schedule II [269]Alien Dictionary [329]Longest Increasing Path in a ...
随机推荐
- 13 November
[HEOI2015] 定价 BZOJ 4027: 在市场上有很多商品的定价类似于 999 元.4999 元.8999 元这样.它们和 1000 元.5000 元和 9000 元并没有什么本质区别,但是 ...
- electron原来这么简单----打包你的react、VUE桌面应用程序
也许你不甘心只写网页,被人叫做"他会写网页",也许你有项目需求,必须写桌面应用,然而你只会前端,没关系.网上的教程很多,但是很少有能说的浅显易懂的,我尽力将electron打包应用 ...
- React-Native 之 GD (十四)小时风云榜 及 当前时间操作 及 上一小时、下一小时功能实现
1.小时风云榜 GDHourList.js /** * 小时风云榜 */ import React, { Component } from 'react'; import { StyleSheet, ...
- ssh连接MAC服务器显示No route to host解决方法
首先MAC操作系统是10 其它电脑通过ssh访问一台mac服务器时,有时候可以登录进去,有显示显示no route to host 并且通过浏览器访问布署在mac上的jenkins,反应奇慢,后来做了 ...
- python常用包官网
Pandas http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.reset_index.html?high ...
- 请正视抑郁症(附Zung氏抑郁自评量表(SDS))
为什么要记录? 因为去年开始关注抑郁症这块,逐渐发现抑郁症原来不只是简单的情绪问题,它是情绪与实质性的生理相互作用并紧密关联的疾病,并不是单纯的劝解自己就可以疗愈的一种疾病,它的存在需要换着身边的人帮 ...
- python字典-字典方法
1.kyes() (1)取出字典的key In [32]: myCat Out[32]: {'colr': 'gray', 'size': 'fat'} In [33]: for i in myCat ...
- python函数-语句
一.def语句和参数 #!/usr/bin/env python #coding:utf-8 def hello(name): print('Hello ' +name) hello('dingkai ...
- Maven 标准项目结构
项目结构 src main java 源文件 resources 资源文件 filters 资源过滤文件 config 配置文件 scripts 脚本文件 webap ...
- C#Exception 追踪异常位置
1:在编写软件时,保护关键位置的代码正常运行,要对这位置进行异常处理try catch private void StartTCPServer() { try { ........//我们要确保知道这 ...