1. 程式人生 > >Weekly Contest 96(-1)

Weekly Contest 96(-1)

分析:從示例2中我們可以知道題中所謂’頂部’、‘前面‘’和‘側面’投影的定義,面積計算也由此迎刃而解。

class Solution {
public:
    int projectionArea(vector<vector<int>>& grid) {
        int len1 = grid.size(), len2 = grid[0].size(); //
        int ans = 0;
        //top
        for(int x = 0; x < len1; x++) {
            for(int y = 0; y < len2; y++) {
                if
(grid[x][y]) ans++; // } } //front for(int x = 0; x < len1; x++) { int max_h = 0; for(int y = 0; y < len2; y++) { if(grid[x][y] > max_h) max_h = grid[x][y]; } ans += max_h; } //side for
(int y = 0; y < len2; y++) { int max_h = 0; for(int x = 0; x < len1; x++) { if(grid[x][y] > max_h) max_h = grid[x][y]; } ans += max_h; } return ans; } };
class Solution {
public:
    //貪心
    int numRescueBoats(vector
<int>
& people, int limit) { int min_shapes = 0; sort(people.begin(), people.end()); int low = 0, high = people.size()-1; while(high > low) { min_shapes++, high--; if(people[high+1] == limit || people[high+1]+people[low] > limit) continue; low++; } if(high == low) min_shapes++; return min_shapes; } };

3. 884. 索引處的解碼字串
題目:
週期性
週期性
分析:如果每次在判斷S中的字元後簡單地進行字元或字串的連線(o(new_length)),那麼當K足夠大時,必然超時。我們注意到, max(S.length)不大,超時的“罪魁禍首”在於大量的重複連線。實際上,這些重複連線是不必做的,即不儲存當前解碼字串而只用cur_len標記當前的解碼長度,當解碼第i個字元為數字時,如果cur_len*repeat_cnt>=K,則直接返回decodeAtIndex(S.substr(0,i),(K-1)%cur_len+1)(週期性)

typedef long long ll;
class Solution {
public:
    string decodeAtIndex(string S, int K) { //從S的解碼字串中返回第K個字母
        int cur_len = 0;
        for(int i = 0; i < S.length(); i++) {
            if(isdigit(S[i])) {
                int repeat_cnt = S[i]-'0';
                if((ll)cur_len*repeat_cnt >= K)  return decodeAtIndex(S.substr(0, i), (K-1)%cur_len+1);
                cur_len *= repeat_cnt;
            }
            else {
                if(++cur_len == K) {
                    string ans = "";
                    return (ans += S[i]);
                }
            }
        }
    }
};