LeetCode笔记(array:)

118 - 119 - 134.

118. 杨辉三角

在这里插入图片描述
错位相加,最后添个1

// 15.18
// 15.25
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        if(!numRows) return {};

        vector<vector<int>> ans = {{1}};
        vector<int> tmp;
        for(int i = 1; i < numRows; i++) {
            tmp.clear();
            tmp.push_back(1);
            for(int k = 1; k < i; k++) {
                tmp.push_back(ans[i-1][k]+ans[i-1][k-1]);
            }
            tmp.push_back(1);
            ans.push_back(tmp);
        }

        return ans;
    }
};

119. 杨辉三角 II

在这里插入图片描述

// 15.35
// 15.39
class Solution {
public:
    vector<int> getRow(int rowIndex) {
        if(!rowIndex) return {1};

        vector<int> ans(rowIndex+1, 1);
        for(int i = 1; i < rowIndex+1; i++) {
            for(int k = i-1; k >= 1; k--) 
                ans[k] = ans[k] + ans[k-1];
        }

        return ans;
    }
};

134. 加油站在这里插入图片描述

// 15.42
// 16.08
// O(n^2) 最简单的想法就是模拟整个循环过程
class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        if(gas.empty() || cost.empty()) return -1;

        int start, curr;
        for(start = 0; start < gas.size(); start++) {
            int cnt = 1, sum = gas[start]-cost[start], curr = start;
            while(cnt != gas.size() && sum >= 0) {
                cnt++;
                curr = (curr+1) % gas.size();
                sum += gas[curr]-cost[curr];
            }
            if(cnt == gas.size() && sum >= 0) {
                return start;
            }
        }

        return -1;
    }
};
// 看答案的解法,但也只是一知半解O(n)
class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        if(gas.empty() || cost.empty()) return -1;

        int sum = 0, lowest = gas.front() + 1, index = 0;
        for(int i = 0; i < gas.size(); i++) {
            sum += gas[i] - cost[i];
            if(sum < lowest) {
                index = i;
                lowest = sum;
            }
        }
        if(sum < 0) return -1;
        //return (index)? (index + 1) % gas.size() : 0;
        return (index + 1) % gas.size();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值