Leetcode进阶之路——Weekly Contest 153

37 篇文章 0 订阅

1184. Distance Between Bus Stops
distance
给定一个distance数组,distance[i]表示从i到i(+1) % n的距离,返回从start 到 destination的最短路径
由于必定是一个环,因此有两种路径,顺时针和逆时针
先用一个前缀和判断某个方向(如顺时针),用总距离与之相减即为另一方向的距离,返回两者中较小值

class Solution {
public:
    int distanceBetweenBusStops(vector<int>& distance, int start, int destination) {
		int len = distance.size();
		if (start == destination) return 0;
		if (start > destination)
		{
			start ^= destination;
			destination ^= start;
			start ^= destination;
		}
		vector<int> presum(len + 1, 0);
		for (int i = 0; i < distance.size(); ++i)
			presum[i + 1] = presum[i] + distance[i];
		
		int dis = presum[destination] - presum[start];
		return min(presum.back() - dis, dis);
	}
};

1185. Day of the Week
day of the week
给定日期,包含年月日,返回该日是星期几,其中年份从1971到2020
查日历的值1971.1.1是周五,因此计算从给定的日期到1971.1.1共有多少天,对7取余即可

class Solution {
public:
    string dayOfTheWeek(int day, int month, int year) {
        set<int> mon1 = {1, 3, 5, 7, 8, 10, 12};
        string res[] = {"Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"};
        int amount = 0;
        for(int i = 1971; i < year; ++i)
        {
            if(i % 400 == 0 || (i % 4 == 0 && i % 100 != 0)) amount += 366;
            else amount += 365;
        }
        for(int i = 1; i < month; ++i)
        {
            if(mons.find(i) != mons.end()) amount += 31;
            else amount += 30;
        }
        if(month > 2)
        {
            if(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) amount--;
            else amount -=2;
        }
        amount += day;
        return res[(amount- 1) % 7];
    }
};

1186. Maximum Subarray Sum with One Deletion
1186
给定一个数组,若最多只能删除一个数,返回最大的子序列和
首先根据53. Maximum Subarray的方法,可以得到若不删除任意一个数字,到各位的子序列和最大为多少
那么分两轮,第一轮从前往后得到数组forward(同时更新若不删除,所能得到的最大和)
第二轮从后往前遍历得到数组backward,那么若删除第i位,所能得到的最大和为forward[i - 1] + backward[i + 1],即可求得

class Solution {
public:
    int maximumSum(vector<int>& arr) {
		int len = arr.size();
		vector<int> forward(len), backward(len);
		forward[0] = arr[0];
		int res = arr[0];
		for (int i = 1; i < len; ++i)
		{
			forward[i] = max(arr[i], forward[i - 1] + arr[i]);
			res = max(res, forward[i]);
		}
		
		backward.back() = arr.back();
		for (int i = len - 2; i >= 0; --i)
		{
			backward[i] = max(backward[i + 1] + arr[i], arr[i]);
			res = max(res, backward[i]);
		}
		
		for (int i = 1; i < len - 1; ++i)
		{
			res = max(res, backward[i + 1] + forward[i - 1]);
		}
		return res;
	}
};

1187. Make Array Strictly Increasing
1187
暂时还没做出来… anyone can help?

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值