7.27

1.第一题:
7.27_第1张图片

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        n=len(nums)
        demo=[i for i in range(n+1)]
        for num in nums:
            if num in demo:
                demo.remove(num)
        return demo[0]

2.第二题:
7.27_第2张图片
首先我的暴力解法,每次移一位,总共移k次,只不过通不过所有的测试用例,代码如下,太垃圾了。

class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        def mov(head):
            p=head
            while head.next.next:
                head=head.next
                if head.next.next==None:
                    break
            s=head.next
            s.next=p
            head.next=None
            return s
        if head==None or head.next==None:
            return head
        for i in range(k):
            head=mov(head)
        return head

然后看了下官方题解,先将链表连成环,然后找到新链表的头和尾然后再断开,其中head在n-k%n处,tail在n-k%n+1处,代码如下:

class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        n=1
        if head==None or head.next==None:
            return head
        old_tail=head
        while old_tail.next:
            old_tail=old_tail.next
            n+=1
        #连成环
        old_tail.next=head
        #找到新的链表头 n-k%n 新的链表尾 n-k%n-1
        new_tail=head
        for i in range(n-k%n-1):
            new_tail=new_tail.next
        new_head=new_tail.next
        new_tail.next=None
        return new_head

你可能感兴趣的:(leecode刷题,leetcode)