Leetcode第52场双周赛write up

  • 将句子排序

    第一步就是将句子进行分割,分割之后存在列表中,因为分割之后每个单词后面都有对应的数字,而且数字是唯一的,因此可以通过字典对数字进行排序,排序之后根据字典的key遍历即可。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    class Solution(object):
    def sortSentence(self, s):
    """
    :type s: str
    :rtype: str
    """
    d = {}
    s1=""
    res = s.split(" ")
    for i in res:
    d[int(i[-1])] = i[:-1]
    for i in d.keys():
    s1+=d[i]
    s1+=" "
    return s1[:-1]
  • 增长的内存泄露

    首先需要设定一个不断增长的内存数,之后需要思考一下循环退出条件,即当内存数都大于两个内存条的可用内存时就退出。在循环中需要用较大的可用内存条数减去当前的内存数,最后通过一个列表接受三个值即可。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    class Solution(object):
    def memLeak(self, memory1, memory2):
    """
    :type memory1: int
    :type memory2: int
    :rtype: List[int]
    """
    res = []
    i = 1
    while i<=memory1 or i<=memory2:
    if memory1>=memory2:
    memory1-=i
    i+=1
    else:
    memory2-=i
    i+=1
    res.append(i)
    res.append(memory1)
    res.append(memory2)
    return res
  • 旋转盒子

    此题可以先在旋转之间将字符的改变位置设定好,最后再进行一次顺时针旋转即可。具体是对矩阵的每一行进行单独操作,遍历每一行,如果是石头则累计石头的个数,如果遇到障碍物,则将石头的个数清零,如果遇到空位置,则需要将前面累计的石头一次延续到这个空位置,并将前面累计的第一个石头的位置设为空位置。最后将矩阵进行一次顺时针旋转即可。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    class Solution(object):
    def rotateTheBox(self, box):
    """
    :type box: List[List[str]]
    :rtype: List[List[str]]
    """
    for i in box:
    count=0
    for j in range(len(i)):
    if i[j]=="#":
    count+=1
    elif i[j]=="*":
    count=0
    elif i[j]==".":
    if count!=0:
    i[j-count]="."
    i[j]="#"
    box[::] = zip(*box[::-1])
    return box
  • 向下取整数对和

    排序后进行二分查找

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    class Solution(object):
    def sumOfFlooredPairs(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    ans = 0
    mod = 1000000007
    nums = sorted(nums)
    n = len(nums)
    for i in range(n):
    j=1
    while nums[i] * j <= nums[n-1]: #判断是否小于最大值
    start = self.binarySearch(nums, nums[i] * j) #找到大于等于nums[i] * j的下标
    ans = (ans + n - start) % mod
    j+=1
    return ans

    def binarySearch(self,nums,x):
    l,r= 0,len(nums)-1
    while l < r :
    mid = (l+(r-1))//2
    if nums[mid] >= x:
    r=mid
    else:
    l=mid+1
    return r