Weekly Contest 96(-1)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值