Weekly Contest 96(-1)

版权声明:欢迎指出文章不足之处~~~ https://blog.csdn.net/zhui_xiuge/article/details/81513663

1. 887. 三维形体投影面积

分析:从示例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;
    }
};

2 . 885. 救生艇

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]);
                }
            }
        }
    }
};

参照:
【1】:yubowenok

猜你喜欢

转载自blog.csdn.net/zhui_xiuge/article/details/81513663
今日推荐