LeetCode 1359、1360

简介: LeetCode 1359、1360

LeetCode 1359. 有效的快递序列数目

题目:

给你 n 笔订单,每笔订单都需要快递服务。
请你统计所有有效的 收件/配送 序列的数目,确保第 i 个物品的配送服务 delivery(i) 总是在其收件服务 pickup(i) 之后。
由于答案可能很大,请返回答案对 10^9 + 7 取余的结果。

示例 :

输入:n = 1
输出:1
解释:只有一种序列 (P1, D1),物品 1 的配送服务(D1)在物品 1 的收件服务(P1)后

思路

代码:

class Solution {
public:
    int countOrders(int n) {
        const int MOD = 1e9 + 7;
        long long res = 1;
        for (int i = 1; i <= 2*n; i ++) {
            if (i % 2) res = res * i % MOD;
            else res = i / 2 * res % MOD;  //2n个数中各有n个偶数和奇数,除去n个2即2^n
        }
        return res;
    }
};

LeetCode 1360 日期之间隔几天

题目:

请你编写个程序来计算两个日期之间隔了多少天。 
日期以字符串形式给出,格式为YwY. M-DD,如示例所示。

示例 :

输入: date1 = "2019 06-29”,date2 =" 2019-06-30
输出: 1

思路

代码:

class Solution {
public:
    int daysBetweenDates(string date1, string date2) {
        return abs(get(date1) - get(date2));
    }
    //判断是否为闰年
    bool is_leap(int year) {
        if (year % 100 && year % 4 == 0 || year % 400 == 0)
            return 1;
        else return 0;
    }
    //用数组存每个月的天数
    int m_day[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int get(string date) {
        int year, month, day;
        sscanf(date.c_str(), "%d-%d-%d", &year, &month, &day);
        int days = 0;
        for (int i = 1971; i < year; i ++) days += 365 + is_leap(i);  //按年算
        for (int i = 1; i < month; i ++) {  //按月算
            if (i == 2) days += 28 + is_leap(year);  
            else days += m_day[i];
        }
        return days += day; 
    }
};

sscanf() 与c_str()

sscanf的原型:

#include <stdio.h>
int sscanf(const char *str, const char *format, ...);
str:待解析的字符串;
format:字符串格式描述;
其后是一序列数目不定的指针参数,存储解析后的数据.

举例

int year, month, day;
int converted = sscanf("20191103", "%04d%02d%02d", &year, &month, &day);
printf("converted=%d, year=%d, month=%d, day=%d/n", converted, year, month, day);
 输出:converted=3, year=2019, month=11, day=03

c_str 的函数原型:

//c_str()函数返回一个指向正规C字符串的指针, 内容与本字符串相同. 
  const char *c_str();

充电站

推荐一个零声学院免费公开课程,个人觉得老师讲得不错,分享给大家:Linux,Nginx,ZeroMQ,MySQL,Redis,fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,TCP/IP,协程,DPDK等技术内容,立即学习

相关文章
|
3月前
leetcode-827:最大人工岛
leetcode-827:最大人工岛
25 0
|
10月前
单链表反转 LeetCode 206
单链表反转 LeetCode 206
53 0
|
11月前
顺手牵羊(LeetCode844.)
好多同学说这是双指针法,但是我认为叫它顺手牵羊法更合适
47 0
|
算法
LeetCode——944. 删列造序
LeetCode——944. 删列造序
84 0
LeetCode 389. 找不同
给定两个字符串 s 和 t,它们只包含小写字母。
50 0
|
测试技术
一和零(LeetCode-474)
一和零(LeetCode-474)
110 0
一和零(LeetCode-474)
|
机器学习/深度学习
LeetCode:605. 种花问题
LeetCode:605. 种花问题
90 0
leetcode
在排序数组中查找元素的第一个和最后一个位置

热门文章

最新文章