【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

 1 class Solution {
 2 public:
 3     bool increasingTriplet(vector<int>& nums) {
 4         int min1 = INT_MAX, min2 = INT_MAX;
 5         for (auto& num : nums) {
 6             if (num > min2) {return true;}
 7             else if (num < min1) {
 8                 min1 = num;
 9             } else if (min1 < num && num < min2) {
10                 min2 = num;
11             }
12         }
13         return false;
14     }
15 };
View Code

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

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

The string "dir subdir1 file1.ext subsubdir1 subdir2 subsubdir2 file2.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表示当前的层级。一行一行处理,用' '分割行,用' '的个数来决定层级。

 1 class Solution {
 2 public:
 3     int lengthLongestPath(string input) {
 4         const int n = input.size();
 5         vector<int> stk; //
 6         int start = 0, end = 0;
 7         int res = 0;
 8         while (end < n) { //这个while循环处理一行
 9             int level = 0;
10             if (input[end] == '	') { //处理前面的 /t 的个数,决定当前的层级
11                 while (end < n && input[end] == '	') { ++level; ++end;}
12             }         
13             while (stk.size() > level) { stk.pop_back(); }     
14             string word = "";
15             while (end < n && input[end] != '
') { //归档当前的文件夹的名称,和文件名称
16                 word += input[end];
17                 ++end;
18             }
19             int temp = word.size() + (stk.empty() ? 0 : stk.back()) + 1;
20             stk.push_back(temp);
21             if (temp > res) {
22                 int p = word.find('.');
23                 if (p != string::npos && p < word.size() - 1) {
24                     res = temp;
25                 }
26             }
27             if (end < n && input[end] == '
') {++end;}
28         }
29         return res == 0 ? res : res - 1;
30     }
31 };
View Code

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

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

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

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

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

 1 class Solution {
 2 public:
 3     int countBattleships(vector<vector<char>>& board) {
 4         n = board.size();
 5         m = board[0].size();
 6         int ret = 0;
 7         for (int i = 0; i < n; ++i) {
 8             for (int j = 0; j < m; ++j) {
 9                 if (board[i][j] == '.') {continue;}
10                 if ((i == 0 || board[i-1][j] != 'X') && (j == 0 || board[i][j-1] != 'X')) {ret++;}
11             }
12         }
13         return ret;
14     }
15     int n, m;
16 };
View Code

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

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

题解:递归

 1 /*
 2 // Definition for a QuadTree node.
 3 class Node {
 4 public:
 5     bool val;
 6     bool isLeaf;
 7     Node* topLeft;
 8     Node* topRight;
 9     Node* bottomLeft;
10     Node* bottomRight;
11 
12     Node() {}
13 
14     Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
15         val = _val;
16         isLeaf = _isLeaf;
17         topLeft = _topLeft;
18         topRight = _topRight;
19         bottomLeft = _bottomLeft;
20         bottomRight = _bottomRight;
21     }
22 };
23 */
24 class Solution {
25 public:
26     Node* construct(vector<vector<int>>& grid) {
27         const int n = grid.size();
28         vector<int> tl = {0, 0}, br = {n-1, n-1};
29         return construct(grid, tl, br);
30     }
31     Node* construct(vector<vector<int>>& grid, vector<int> tl, vector<int> br) {
32         if (tl == br) {
33             Node* root = new Node(grid[tl[0]][tl[1]], true, nullptr, nullptr, nullptr, nullptr);
34             return root;
35         }
36         int t = tl[0], b = br[0], l = tl[1], r = br[1];
37         bool split = false;
38         for (int i = t; i <= b; ++i) {
39             for (int j = l; j <= r; ++j) {
40                 if (grid[i][j] != grid[t][l]) {
41                     split = true;
42                 }
43             }
44         }
45         if (!split) {
46             Node* root = new Node(grid[tl[0]][tl[1]], true, nullptr, nullptr, nullptr, nullptr);
47             return root;
48         }
49         Node* root = new Node(0, false, nullptr, nullptr, nullptr, nullptr);
50         int newx = (t + b) / 2, newy = (l + r) / 2;
51         root->topLeft = construct(grid, tl, {newx, newy});
52         root->topRight = construct(grid, {t, newy+1}, {newx, r});
53         root->bottomLeft = construct(grid, {newx + 1, l}, {b, newy});
54         root->bottomRight = construct(grid, {newx+1, newy+1}, br);
55         return root;
56     }
57 };
View Code

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

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

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

 1 class Solution {
 2 public:
 3     int minMutation(string start, string end, vector<string>& bank) {
 4         const int n = bank.size();
 5         vector<int> visit(n, 0);
 6         queue<string> que;
 7         que.push(start);
 8         int step = 0;
 9         int ret = -1;
10         while (!que.empty()) {
11             step++;
12             const int size = que.size();
13             for (int i = 0; i < size; ++i) {
14                 string cur = que.front(); que.pop();
15                 for (int k = 0; k < n; ++k) {
16                     if (visit[k]) {continue;}
17                     if (diff(bank[k], cur) == 1) {
18                         visit[k] = 1;
19                         que.push(bank[k]);
20                         if (bank[k] == end) {
21                             ret = step;
22                             return ret;
23                         }
24                     }
25                 }
26             }
27         }
28         return ret;
29     }
30     int diff (string s1, string s2) {
31         if (s1.size() != s2.size()) {return -1;}
32         int cnt = 0;
33         for (int i = 0; i < s1.size(); ++i) {
34             if (s1[i] != s2[i]) {
35                 ++cnt;
36             }
37         } 
38         return cnt;
39     }
40 };
View Code

【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 就可以了。

 1 class Solution {
 2 public:
 3     int magicalString(int n) {
 4         if (n == 0) {return 0;}
 5         string s = "122";
 6         int idx = 2, res = 1;
 7         while (s.size() < n) {
 8             char c = '3' - s.back() + '0';
 9             if (s[idx] == '1') {
10                 s.push_back(c);  
11                 if (s.size() <= n && c == '1') {++res;}
12             } else {
13                 s.push_back(c);  
14                 if (s.size() <= n && c == '1') {++res;}
15                 s.push_back(c);  
16                 if (s.size() <= n && c == '1') {++res;}
17             }
18             ++idx;
19         }
20         return res;
21     }
22 };
View Code

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

Given an integer, return its base 7 string representation.

Example 1:
Input: 100
Output: "202"

Example 2:
Input: -7
Output: "-10"

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

题解:直接按照进制转换

 1 class Solution {
 2 public:
 3     string convertToBase7(int num) {
 4         bool negative = false;
 5         if (num < 0) {
 6             negative = true;
 7             num = -num;
 8         }
 9         string ret = "";
10         while (num != 0) {
11             int mod = num % 7;
12             num = num / 7;
13             ret = to_string(mod) + ret;
14         }
15         ret = negative ? "-" + ret : ret;
16         ret = ret == "" ? "0" : ret;
17         return ret;
18     }
19 };
View Code

【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 1:
Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
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.
 1 class Solution {
 2 public:
 3     vector<string> findRelativeRanks(vector<int>& nums) {
 4         const int n = nums.size();
 5         map<int, int, greater<int>> mp;
 6         for (int i = 0; i < nums.size(); ++i) {
 7             int score = nums[i];
 8             mp[score] = i;
 9         }
10         vector<string> ret(n);
11         int cnt = 1;
12         for (auto e : mp) {
13             int idx = e.second;
14             if (cnt <= 3) {
15                 if (cnt == 1) {
16                     ret[idx] = "Gold Medal";
17                 }
18                 if (cnt == 2) {
19                     ret[idx] = "Silver Medal";
20                 }
21                 if (cnt == 3) {
22                     ret[idx] = "Bronze Medal";
23                 }
24                 ++cnt;
25             } else {
26                 ret[idx] = to_string(cnt++);
27             }
28         }
29         return ret;
30     }
31 };
View Code

【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。

 1 class Solution {
 2 public:
 3     int singleNonDuplicate(vector<int>& nums) {
 4         const int n = nums.size();
 5         int left = 0, right = n;
 6         while (left < right) {
 7             int mid = (left + right) / 2;
 8             int partner = mid % 2 == 0 ? mid + 1 : mid - 1;
 9             if (nums[mid] == nums[partner]) {
10                 left = mid + 1;
11             } else {
12                 right = mid;   
13             }
14         }
15         return nums[left];
16     }
17 };
View Code

【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可以解。

 1 class Solution {
 2 public:
 3     vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
 4         n = graph.size();
 5         vector<vector<int>> paths;
 6         vector<int> path(1, 0);
 7         dfs(graph, paths, path);
 8         return paths;
 9     }
10     void dfs(const vector<vector<int>>& graph, vector<vector<int>>& paths, vector<int>& path) {
11         if (path.back() == n-1) {
12             paths.push_back(path);
13             return;
14         }
15         int node = path.back();
16         for (auto adj : graph[node]) {
17             path.push_back(adj);
18             dfs(graph, paths, path);
19             path.pop_back();
20         }
21     }
22     int n;
23 };
View Code
原文地址:https://www.cnblogs.com/zhangwanying/p/10016508.html