【LeetCode】未分類(tag裏面沒有)(共題)

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

給了一個數組 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.
ide

題解:能夠dp作,LIS 最少 nlog(n)。 這個題能夠greedy,能夠作到O(N). 咱們用兩個變量,min1 表示當前最小的元素,min2表示當前第二小的元素。能夠分紅三種狀況討論:ui

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

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

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

 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,沒分類)3d

給了一個string表明一個文件目錄的層級。code

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'的個數來決定層級。

 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') { //處理前面的 /t 的個數,決定當前的層級
11                 while (end < n && input[end] == '\t') { ++level; ++end;}
12             }         
13             while (stk.size() > level) { stk.pop_back(); }     
14             string word = "";
15             while (end < n && input[end] != '\n') { //歸檔當前的文件夾的名稱,和文件名稱
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] == '\n') {++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
相關文章
相關標籤/搜索