Leetcode进阶之路——Weekly Contest 153

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

class Solution {
public:
    int distanceBetweenBusStops(vector& distance, int start, int destination) {
		int len = distance.size();
		if (start == destination) return 0;
		if (start > destination)
		{
			start ^= destination;
			destination ^= start;
			start ^= destination;
		}
		vector 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
Leetcode进阶之路——Weekly Contest 153_第2张图片
给定日期,包含年月日,返回该日是星期几,其中年份从1971到2020
查日历的值1971.1.1是周五,因此计算从给定的日期到1971.1.1共有多少天,对7取余即可

class Solution {
public:
    string dayOfTheWeek(int day, int month, int year) {
        set 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
Leetcode进阶之路——Weekly Contest 153_第3张图片
给定一个数组,若最多只能删除一个数,返回最大的子序列和
首先根据53. Maximum Subarray的方法,可以得到若不删除任意一个数字,到各位的子序列和最大为多少
那么分两轮,第一轮从前往后得到数组forward(同时更新若不删除,所能得到的最大和)
第二轮从后往前遍历得到数组backward,那么若删除第i位,所能得到的最大和为forward[i - 1] + backward[i + 1],即可求得

class Solution {
public:
    int maximumSum(vector& arr) {
		int len = arr.size();
		vector 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
Leetcode进阶之路——Weekly Contest 153_第4张图片
暂时还没做出来… anyone can help?

你可能感兴趣的:(C++,leetcode,C++,leetcode)