查看: 8352| 回复: 117
跳转到指定楼层
上一主题 下一主题
收起左侧

Leetcode 刷题打卡记录 包括Solution

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
已经刷了几十道了,从今天开始争取每天打卡,同时把之前的也逐渐贴上来。
0060 Permutation Sequence
  1. // 自己的解法,效率不高
  2. // 484ms, 12.9%, 2019.1.26
  3. class Solution {
  4. private:
  5.     string buf;
  6.     int idx;
  7.     vector<bool> flags;
  8. public:
  9.     bool getPerm(int n, int k, int start) {
  10.         if (start == n) {
  11.             idx++;
  12.             return idx == k;
  13.         }
  14.         for (int i = 0; i < n; i++) {
  15.             if (flags) continue;
  16.             flags = true;
  17.             char c = buf[start];
  18.             buf[start] = '0' + i + 1;
  19.             if (getPerm(n, k, start + 1))
  20.                 return true;
  21.             flags = false;
  22.             buf[start] = c;
  23.         }
  24.         return false;
  25.     }
  26.     string getPermutation(int n, int k) {
  27.         string s(n, ' ');
  28.         flags.resize(n);
  29.         for (int i = 0; i < n; i++) {
  30.             s = '0' + i + 1;
  31.             flags = false;
  32.         }
  33.         buf = s;
  34.         idx = 0;
  35.         
  36.         getPerm(n, k, 0);
  37.         return buf;
  38.     }
  39. };

  40. // 参考了这个帖子的讲解
  41. // [url]https://leetcode.com/problems/permutation-sequence/discuss/22507/%22Explain-like-I'm-five%22-Java-Solution-in-O[/url](n)
  42. // 0ms ,100%
  43. /*
  44. say n = 4, you have {1, 2, 3, 4}

  45. If you were to list out all the permutations you have

  46. 1 + (permutations of 2, 3, 4)

  47. 2 + (permutations of 1, 3, 4)

  48. 3 + (permutations of 1, 2, 4)

  49. 4 + (permutations of 1, 2, 3)
  50. */
  51. class Solution {
  52. public:
  53.     string getPermutation(int n, int k) {
  54.         // calc facts
  55.         vector<int> facs(n + 1);
  56.         facs[0] = 1;
  57.         for (int i = 1; i <= n; i++) {
  58.             facs = i * facs[i-1];
  59.         }
  60.         string nums = "123456789";
  61.         string res;
  62.         for (int i = 1; i <= n; i++) {
  63.             int idx = (k-1) / facs[n-i];
  64.             res += nums[idx];
  65.             nums.erase(nums.begin() + idx);
  66.             k -= idx * facs[n-i];
  67.         }
  68.         return res;
  69.     }
  70. };
复制代码


评分

参与人数 4大米 +19 收起 理由
lbc + 3 给你点个赞!
mwen2 + 1 很有用的信息!
14417335 + 5 给你点个赞!
instant_dev + 10 给你点个赞!

查看全部评分


上一篇:哪里找狗家高频题
下一篇:开帖更新刷题记录 自制力太差了 求组队求监督
推荐
 楼主| wglacier 2019-1-31 19:09:57 | 只看该作者
全局:
0037. Sudoku Solver
  1. class Solution {
  2. private:
  3.     vector<vector<bool>> bufRows = vector<vector<bool>>(9, vector<bool>(256, false));
  4.     vector<vector<bool>> bufCols = vector<vector<bool>>(9, vector<bool>(256, false));
  5.     vector<vector<bool>> bufDias = vector<vector<bool>>(9, vector<bool>(256, false));
  6. public:
  7.     bool isValid(vector<vector<char>>& board, int i, int j, char c) {
  8.         return !bufRows[i][c]
  9.             && !bufCols[j][c]
  10.             && !bufDias[i/3*3 + j/3][c];
  11.     }
  12.     void setFlag(vector<vector<char>>& board, int i, int j, char c, bool value) {
  13.         bufRows[i][c] = value;
  14.         bufCols[j][c] = value;
  15.         bufDias[i/3*3 + j/3][c] = value;
  16.     }
  17.     bool solve(vector<vector<char>>& board, int i, int j) {
  18.         if (i == 9) return true;
  19.         if (j == 9) return solve(board, i+1, 0);
  20.         
  21.         char c = board[i][j];
  22.         if (c != '.') return solve(board, i, j+1);
  23.         
  24.         for (char d = '1'; d <= '9'; d++) {
  25.             if (!isValid(board,i, j, d))
  26.                 continue;
  27.             setFlag(board, i, j, d, true);
  28.             board[i][j] = d;
  29.             if (solve(board, i, j+1))
  30.                 return true;
  31.             board[i][j] = '.';
  32.             setFlag(board, i, j, d, false);
  33.         }
  34.         return false;
  35.     }
  36.     void solveSudoku(vector<vector<char>>& board) {
  37.        for (int i = 0; i < 9; i++) {
  38.            for (int j = 0; j < 9; j++) {
  39.                char c = board[i][j];
  40.                if (c == '.')
  41.                    continue;
  42.                bufRows[i][c] = true;
  43.                bufCols[j][c] = true;
  44.                bufDias[i/3*3 + j/3][c] = true;
  45.            }
  46.        }
  47.         solve(board, 0, 0);
  48.     }
  49. };
  50. ```
  51. ```c++
  52. class Solution {
  53. public:
  54.     bool validatePos(const vector<vector<char>>& board, int i, int j) {
  55.         // vertical
  56.         vector<bool> vcols(9, false);
  57.         for (int m = 0; m < 9; m++) {
  58.             // cols
  59.             if (board[m][j] == '.') continue;
  60.             
  61.             int num = board[m][j] - '1';
  62.             if (vcols[num]) {
  63.                 return false;
  64.             }
  65.             vcols[num] = true;
  66.         }
  67.         // 3x3
  68.         vector<bool> vsqrs(9, false);
  69.         int basei = i/3*3;
  70.         int basej = j/3*3;
  71.         for (int m = 0; m < 9; m++) {
  72.             char c = board[basei+m/3][basej+m%3];
  73.             if (c == '.') continue;
  74.             int num = c - '1';
  75.             if (vsqrs[num]) return false;
  76.             vsqrs[num] = true;
  77.         }
  78.         return true;
  79.     }
  80.     bool tryNext(vector<vector<char>>& board, vector<vector<bool>>& cache) {
  81.         bool started = false;
  82.         for (int i = 0; i < 9; i++) {
  83.             for (int j = 0; j < 9; j++) {
  84.                 char c = board[i][j];
  85.                 if (c != '.') continue;
  86.                
  87.                 // try every possible values
  88.                 for (int m = 0; m < 9; m++) {
  89.                     if (!cache[i][m]) continue;

  90.                     board[i][j] = m + '1';
  91.                     cache[i][m] = false;
  92.                     if (validatePos(board, i, j)
  93.                         && tryNext(board, cache)) {
  94.                         return true;
  95.                     }
  96.                     board[i][j] = '.';
  97.                     cache[i][m] = true;
  98.                 }
  99.                 // tried every possible ways still no luck, must have made a wrong attempt
  100.                 return false;
  101.             }
  102.         }
  103.         // nothing left to guess
  104.         return true;
  105.     }
  106.     void solveSudoku(vector<vector<char>>& board) {
  107.         // pre-calc per row
  108.         vector<vector<bool>> cache(9, vector<bool>(9, true));
  109.         for (int i = 0; i < 9; i++) {
  110.             for (int j = 0; j < 9; j++) {
  111.                 char c = board[i][j];
  112.                 if (c != '.') {
  113.                     cache[i][c - '1'] = false;
  114.                 }
  115.             }
  116.         }
  117.         tryNext(board, cache);
  118.     }
  119. };
复制代码
回复

使用道具 举报

推荐
 楼主| wglacier 2019-3-21 05:26:56 | 只看该作者
全局:
30. Substring with Concatenation of All Words
Solution 2 using Trie, 44ms
  1. class Trie {
  2.     Trie *cc[26];
  3.     int pos;
  4. public:
  5.     Trie() {
  6.         pos = -1;
  7.         fill_n(cc, 26, nullptr);
  8.     }
  9.     void insert(const string &s, int position) {
  10.         Trie* p = this;
  11.         for (auto &c : s) {
  12.             int idx = c - 'a';
  13.             if (!p->cc[idx]) {
  14.                 p->cc[idx] = new Trie();
  15.             }
  16.             p = p->cc[idx];
  17.         }
  18.         p->pos = position;
  19.     }
  20.     int search(const string &s, int start, int sz) {
  21.         Trie* p = this;
  22.         for (int i = start; i < start + sz; i++) {
  23.             int idx = s[i] - 'a';
  24.             if (!p->cc[idx]) return -1;
  25.             p = p->cc[idx];
  26.         }
  27.         return p->pos;
  28.     }
  29. };

  30. class Solution {
  31. public:
  32.     vector<int> findSubstring(string s, vector<string>& words) {
  33.         vector<int> res;
  34.         if (words.empty() || s.empty())
  35.             return res;
  36.         unordered_map<string,int> mm;
  37.         for (auto &w : words) {
  38.             mm[w]++;
  39.         }
  40.         vector<int> flagTmpl(mm.size(), 0);
  41.         Trie trie;
  42.         int i = 0;
  43.         for (auto itt : mm) {
  44.             flagTmpl[i] = itt.second;
  45.             trie.insert(itt.first, i);
  46.             i++;
  47.         }

  48.         vector<int> dp(s.size(), -2);
  49.         const int WD_LEN = words[0].size();
  50.         for (int i = 0; i <= (int)s.size()-(int)(WD_LEN*words.size()); i++) {
  51.             if (dp[i] == -1) continue;

  52.             vector<int> flags(flagTmpl);
  53.             int flagCount = 0;
  54.             int start = i;
  55.             while (flagCount < words.size() && start <= s.size() - WD_LEN) {
  56.                 int pos = dp[start];
  57.                 if (pos == -1) break;
  58.                 if (pos == -2) {
  59.                     pos = trie.search(s, start, WD_LEN);
  60.                 }
  61.                 if (pos < 0) {
  62.                     dp[start] = -1;
  63.                     break;
  64.                 }
  65.                 if (flags[pos] < 1) {
  66.                     break;
  67.                 }
  68.                 flags[pos]--;
  69.                 dp[start] = pos;
  70.                 start += WD_LEN;
  71.                 ++flagCount;
  72.             }
  73.             if (flagCount == words.size()) {
  74.                 res.push_back(i);
  75.             }
  76.         }
  77.         return res;
  78.     }
  79. };
复制代码

回复

使用道具 举报

推荐
 楼主| wglacier 2019-1-30 14:36:00 | 只看该作者
全局:
0068 Text Justification, hard

  1. // 0ms
  2. class Solution {
  3. private:
  4.     string outputOneJustify(vector<string> wbuf, int maxWidth, int len) {
  5.         // `len` is the total length of all words and one space between words
  6.         // words length without any spaces
  7.         int wlen = len - (wbuf.size() - 1);
  8.         int spacesLeft = maxWidth - wlen;
  9.         string res;
  10.         for (string& ws : wbuf) {
  11.             if (!res.empty()) {
  12.                 res += string(spacesLeft/(wbuf.size()-1), ' ');
  13.                 int extraSpaces = spacesLeft % (wbuf.size()-1);
  14.                 if (extraSpaces > 0) {
  15.                     res += string(1, ' ');
  16.                     spacesLeft--;
  17.                 }
  18.             }
  19.             res += ws;            
  20.         }
  21.         if (res.size() < maxWidth) {
  22.             res += string(maxWidth - res.size(), ' ');
  23.         }
  24.         return res;
  25.     }
  26. public:
  27.     vector<string> fullJustify(vector<string>& words, int maxWidth) {
  28.         int len = 0;
  29.         vector<string> wbuf;
  30.         vector<string> resStrs;
  31.         for (string& s : words) {
  32.             // every word needs a space before it except the first one
  33.             if (len > 0) ++len;
  34.             
  35.             if (len + s.size() <= maxWidth) {
  36.                 wbuf.push_back(s);
  37.                 len += s.size();
  38.             } else {
  39.                 len--;

  40.                 string res = outputOneJustify(wbuf, maxWidth, len);
  41.                 resStrs.push_back(res);

  42.                 len = s.size();
  43.                 wbuf.clear();
  44.                 wbuf.push_back(s);
  45.             }
  46.         }
  47.         // last line
  48.         if (len > 0) {
  49.             string res;
  50.             for (string& s : wbuf) {
  51.                 if (!res.empty()) {
  52.                     res += string(1, ' ');
  53.                 }
  54.                 res += s;
  55.             }
  56.             if (res.size() < maxWidth) {
  57.                 res += string(maxWidth - res.size(), ' ');
  58.             }
  59.             resStrs.push_back(res);
  60.         }
  61.         return resStrs;
  62.     }
  63. };
  64. int main(int argc, char* argv[]) {

  65.     vector<string> v = {
  66.         "This", "is", "an", "example", "of", "text", "justification."
  67.     };
  68.     for (string a : Solution().fullJustify(v, 16))
  69.         cout << "'" << a << "'" << endl;
  70.     return 0;
  71. }
复制代码


回复

使用道具 举报

🔗
 楼主| wglacier 2019-1-29 17:47:27 | 只看该作者
全局:
0061 Rotate List


  1. // 4ms, 100%
  2. /**
  3. * Definition for singly-linked list.
  4. * struct ListNode {
  5. *     int val;
  6. *     ListNode *next;
  7. *     ListNode(int x) : val(x), next(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12.     ListNode* rotateRight(ListNode* head, int k) {
  13.         if (head == nullptr)
  14.             return head;

  15.         // get the length
  16.         int len = 0;
  17.         ListNode *p = head;
  18.         while (p != nullptr) {
  19.             len++;
  20.             p = p->next;
  21.         }
  22.         k = k % len;
  23.         if (k == 0) return head;
  24.         
  25.         // make p k steps ahead of q
  26.         p = head;
  27.         ListNode *q = head;
  28.         while (k > 0) {
  29.             k--;
  30.             q = q->next;
  31.         }
  32.         // move to the end
  33.         while(q->next != nullptr) {
  34.             p = p->next;
  35.             q = q->next;
  36.         }
  37.         
  38.         q->next = head;
  39.         head = p->next;
  40.         p->next = nullptr;
  41.         return head;
  42.     }
  43. };
复制代码


回复

使用道具 举报

🔗
 楼主| wglacier 2019-1-29 17:49:00 | 只看该作者
全局:
0062 Unique Paths

  1. // 0ms, 100%
  2. class Solution {
  3. public:
  4.     int uniquePaths(int m, int n) {
  5.         vector<vector<int>> v(m, vector<int>(n, 0));
  6.         for (int i = m-1; i >= 0; i--) {
  7.             for (int j = n-1; j >= 0; j--) {
  8.                 if (i == m-1 || j == n-1) {
  9.                     v[i][j] = 1;
  10.                 } else {
  11.                     v[i][j] =  v[i+1][j] + v[i][j+1];
  12.                 }
  13.             }
  14.         }
  15.         return v[0][0];
  16.     }
  17. };
复制代码

回复

使用道具 举报

🔗
 楼主| wglacier 2019-1-29 17:50:08 | 只看该作者
全局:
0063 Unique Paths II

  1. // 0ms
  2. class Solution {
  3. public:
  4.     int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
  5.         if (obstacleGrid.empty())
  6.             return 0;
  7.         int m = obstacleGrid.size();
  8.         int n = obstacleGrid[0].size();
  9.         
  10.         vector<vector<int>> v(obstacleGrid.size(),
  11.                              vector<int>(obstacleGrid[0].size(), 0));
  12.         if (obstacleGrid[m-1][n-1] == 0)
  13.             v[m-1][n-1] = 1;

  14.         for (int i = m-1; i >= 0; i--) {
  15.             for (int j = n-1; j >= 0; j--) {
  16.                 if (obstacleGrid[i][j] == 1) {
  17.                     continue;
  18.                 }
  19.                 if (i < m-1)
  20.                     v[i][j] += v[i+1][j];
  21.                 if (j < n-1)
  22.                     v[i][j] += v[i][j+1];
  23.             }
  24.         }
  25.         return v[0][0];
  26.     }
  27. };
复制代码

回复

使用道具 举报

🔗
 楼主| wglacier 2019-1-29 17:51:40 | 只看该作者
全局:
0064  Minimum Path Sum

  1. // 4ms, 100%
  2. class Solution {
  3. public:
  4.     int minPathSum(vector<vector<int>>& grid) {
  5.         if (grid.empty())
  6.             return 0;
  7.         int m = grid.size();
  8.         int n = grid[0].size();
  9.         vector<vector<int>> v(m, vector<int>(n, 0));
  10.         v[m-1][n-1] = grid[m-1][n-1];
  11.         for (int i = m-1; i >= 0; i--) {
  12.             for (int j = n-1; j >= 0; j--) {
  13.                 if (i == m-1 && j == n-1)
  14.                     continue;

  15.                 if (i == m-1)
  16.                     v[i][j] = v[i][j+1] + grid[i][j];
  17.                 else if (j == n-1)
  18.                     v[i][j] = v[i+1][j] + grid[i][j];
  19.                 else {
  20.                     v[i][j] = min(v[i][j+1], v[i+1][j]) + grid[i][j];
  21.                 }
  22.             }
  23.         }
  24.         return v[0][0];
  25.     }
  26. };

  27. int main(int argc, char* argv[]) {
  28.     vector<vector<int>> v = {
  29.         {1, 3, 1},
  30.         {1, 5, 1},
  31.         {4, 2, 1}
  32.     };
  33.     cout << Solution().minPathSum(v) << endl;
  34. }
复制代码
回复

使用道具 举报

🔗
 楼主| wglacier 2019-1-30 19:11:43 | 只看该作者
全局:
0069 Sqrt(x)
  1. // 8ms
  2. class Solution {
  3. public:
  4.     int mySqrt(int x) {
  5.         if (x < 1) return x;
  6.         
  7.         long a = 1, b = x;
  8.         while (a <= b) {
  9.             long m = a + (b-a)/2;
  10.             long r = m*m;
  11.             if (r == x) return m;
  12.             if (r > x)
  13.                 b = m-1;
  14.             else
  15.                 a = m+1;
  16.         }
  17.         return b;
  18.     }
  19. };
复制代码
回复

使用道具 举报

🔗
 楼主| wglacier 2019-1-30 19:33:05 | 只看该作者
全局:
0070 Climbing Stairs
  1. // 0ms
  2. class Solution {
  3. public:
  4.     int climbStairs(int n) {
  5.         if (n < 2) return 1;
  6.         
  7.         vector<int> v(n+1, 0);
  8.         v[n] = 1;
  9.         v[n-1] = 1;
  10.         for (int i = n-2; i >= 0; i--) {
  11.             v[i] = v[i+1] + v[i+2];
  12.         }
  13.         return v[0];
  14.     }
  15. };
复制代码
回复

使用道具 举报

🔗
 楼主| wglacier 2019-1-31 05:24:13 | 只看该作者
全局:
0071 Simplify Path
  1. // 4ms
  2. class Solution {
  3. public:
  4.     string simplifyPath(string path) {
  5.         if (path.empty()) return "/";
  6.         
  7.         // prev state:
  8.         //   empty
  9.         //   .
  10.         //   ..
  11.         //   any name, like '.a', '..b', 'abc', etc
  12.         vector<string> vec;
  13.         int i = 0;
  14.         string buf;
  15.         while (i < path.size()) {
  16.             char c = path[i];
  17.             if (c == '/') {
  18.                 if (buf.empty()) {
  19.                     // do nothing
  20.                 } else {
  21.                     if (buf == ".") {
  22.                     }
  23.                     else if(buf == "..") {
  24.                         if (!vec.empty())
  25.                             vec.pop_back();
  26.                     } else {
  27.                         vec.push_back(buf);
  28.                     }
  29.                     buf.clear();
  30.                 }
  31.             } else {
  32.                 buf += string(1, c);
  33.             }
  34.             i++;
  35.         }
  36.         if (!buf.empty()) {
  37.             if (buf == "..") {
  38.                 if (!vec.empty())
  39.                     vec.pop_back();
  40.             }
  41.             else if (buf != ".")
  42.                 vec.push_back(buf);
  43.         }
  44.         string res;
  45.         for (auto& a : vec) {
  46.             res += string("/") + a;
  47.         }
  48.         if (res.empty()) res = "/";
  49.         return res;
  50.     }
  51. };
复制代码
回复

使用道具 举报

🔗
 楼主| wglacier 2019-1-31 16:30:03 | 只看该作者
全局:
0001 Two Sum
  1. class Solution {
  2. public:
  3.     vector<int> twoSum(vector<int>& nums, int target) {
  4.         using node = std::pair<int,int> ;
  5.         vector<node> v;
  6.         for (int i = 0; i < nums.size(); i++) {
  7.             v.push_back(std::make_pair(nums[i], i));
  8.         }
  9.         sort(v.begin(), v.end());
  10.         int i = 0, j = nums.size()-1;
  11.         while (i < j) {
  12.             int d = target - (v[i].first + v[j].first);
  13.             if (d == 0) {
  14.                 vector<int> r = {v[i].second, v[j].second};
  15.                 sort(r.begin(), r.end());
  16.                 return r;
  17.             } else if (d > 0) {
  18.                 i++;
  19.             } else {
  20.                 j--;
  21.             }   
  22.         }
  23.     }
  24. };
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表