1185. Day of the Week

题面:

Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the day, month and year respectively.

Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}.

Example 1:
Input: day = 31, month = 8, year = 2019
Output: "Saturday"

Example 2:
Input: day = 18, month = 7, year = 1999
Output: "Sunday"

Example 3:
Input: day = 15, month = 8, year = 1993
Output: "Sunday"

Constraints:

The given dates are valid dates between the years 1971 and 2100.

思路:

用time库,计算和一个已知日期的时间比对日期差,例如 1970年1月1日是周一,作为基准,计算给定日期到该日的日期差,然后取膜7,即得答案。

coding:

查看time库用法,找到如下:

 1 import time  
 2 import datetime  
 3   
 4 #计算两个日期相差天数,自定义函数名,和两个日期的变量名。  
 5 def Caltime(date1,date2):  
 6     #%Y-%m-%d为日期格式,其中的-可以用其他代替或者不写,但是要统一,同理后面的时分秒也一样;可以只计算日期,不计算时间。  
 7     #date1=time.strptime(date1,"%Y-%m-%d %H:%M:%S")   
 8     #date2=time.strptime(date2,"%Y-%m-%d %H:%M:%S")  
 9     date1=time.strptime(date1,"%Y-%m-%d")  
10     date2=time.strptime(date2,"%Y-%m-%d")  
11     #根据上面需要计算日期还是日期时间,来确定需要几个数组段。下标0表示年,小标1表示月,依次类推...  
12     #date1=datetime.datetime(date1[0],date1[1],date1[2],date1[3],date1[4],date1[5])  
13     #date2=datetime.datetime(date2[0],date2[1],date2[2],date2[3],date2[4],date2[5])  
14     date1=datetime.datetime(date1[0],date1[1],date1[2])  
15     date2=datetime.datetime(date2[0],date2[1],date2[2])  
16     #返回两个变量相差的值,就是相差天数  
17     return date2-date1

然后一顿魔改,得到如下代码:

import time
import datetime

class Solution:
    def Caltime(self, date1, date2):
        date1 = time.strptime(date1, "%Y-%m-%d")
        date2 = time.strptime(date2, "%Y-%m-%d")
        date1 = datetime.datetime(date1[0], date1[1], date1[2])
        date2 = datetime.datetime(date2[0], date2[1], date2[2])
        return date2-date1

    def dayOfTheWeek(self, day, month, year):
        day = str(day)
        month = str(month)
        year = str(year)
        ans_array = ["Monday", "Tuesday", "Wednesday",
                     "Thursday", "Friday", "Saturday", "Sunday"]
        start = "1970-01-01"
        return ans_array[(self.Caltime(start, "-".join([year, month, day])).days+3) % 7]

结果

下午摸鱼继续w


234. Palindrome Linked List

题面:

Given a singly linked list, determine if it is a palindrome.

Example 1:
Input: 1->2
Output: false

Example 2:
Input: 1->2->2->1
Output: true

Follow up:
Could you do it in O(n) time and O(1) space?

思路:

简单的回文判断,直接加到一个list再和reverse作比较就行~
既然有Follow up那就挑战一下:

  • 建立两个指针,一个为fast`,一个为`slow
  • fast`一次移动两个单位,`slow一次移动一个单位,并且使前部链表反转
  • fast`移动至末尾时,`fast指向头
  • fast``slow`均一次移动一个单位,直到`slow`到头,每次移动均比对`fast``slow的值是否一致,如不一致,则不为回文
  • 该链表为回文

coding: