DW&LeetCode_day4(1018、16、20、21)

DW&LeetCode_day4(1018、16、20、21)


Write in front:

  • Start the content of day 4! Come on, friends!

Open source content

Open source content

Study outline 


table of Contents

DW&LeetCode_day4(1018、16、20、21)

Write in front:

Open source content

Study outline 

1018. Binary prefix divisible by 5

answer:

16. The closest sum of three numbers

answer:

20. Valid parentheses

answer:

21. Merge two ordered linked lists

answer:


1018. Binary prefix divisible by 5

Given an array A consisting of a number of 0s and 1s. We define N_i: the i-th sub-array from A[0] to A[i] is interpreted as a binary number (from the most significant bit to the least significant bit).

Return a list of boolean values ​​answer, only when N_i is divisible by 5, answer[i] is true, otherwise it is false.

 

Example 1:

Input: [0,1,1]
Output: [true,false,false]
Explanation: The
input numbers are 0, 01, 011; that is, 0, 1, 3 in decimal. Only the first number is divisible by 5, so answer[0] is true.

Example 2:

Input: [1,1,1]
Output: [false,false,false]


Example 3:

Input: [0,1,1,1,1,1]
Output: [true,false,false,false,true,false]


Example 4:

Input: [1,1,1,0,1]
Output: [false,false,false,false,false]
 

prompt:

1 <= A.length <= 30000
A[i] 为 0 或 1

Link: topic link

answer:

class Solution:
    def prefixesDivBy5(self, A: List[int]) -> List[bool]:
        a = []
        b = 0
        for i in A:
            b = (b * 2 + i)% 5 #将前面的数乘2,再加上新增数并对5取余
            if b  == 0:
                a+=True
            else:
                a+=False
        return a

16. The closest sum of three numbers

Given an array of n integers nums and a target value target. Find the three integers in nums so that their sum is closest to target. Returns the sum of these three numbers. Assume that there is only one answer for each set of inputs.

 

Example:

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The closest sum to target is 2 (-1 + 2 + 1 = 2).
 

prompt:

3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4


Link: topic link

answer:

# python 双指针加排序
class Solution:
    def threeSumClosest(self, a: List[int], target: int) -> int:
        a.sort()
        res = float('inf')
        for i in range(len(a)):
            if i == 0 or a[i]>a[i-1]:                 # 去重
                left = i+1
                right = len(a)-1
                while left<right:
                    b = a[i]+a[left]+a[right]
                    if b == target:
                        return target
                    if abs(b-target)<abs(res-target): # 更新
                        res = b
                    if b < target:
                        left+=1
                    else:
                        right-=1
        return res

20. Valid parentheses

Given a string that only includes'(',')','{','}','[',']', judge whether the string is valid.

A valid string must meet:

The opening bracket must be closed with the same type of closing bracket.
The opening parenthesis must be closed in the correct order.
Note that an empty string can be considered a valid string.

Example 1:

Input: "()"
Output: true


Example 2:

Input: "()[]{}"
Output: true


Example 3:

Input: "(]"
Output: false


Example 4:

Input: "([)]"
Output: false


Example 5:

Input: "{[]}"
Output: true


Link: topic link

answer:

       # python 语法糖
        while '{}' in s or '()' in s or '[]' in s:
            s = s.replace('{}', '')
            s = s.replace('[]', '')
            s = s.replace('()', '')
        return s == ''

21. Merge two ordered linked lists

Combine two ascending linked lists into a new ascending linked list and return. The new linked list is composed by splicing all the nodes of the given two linked lists. 

 

Example 1:

 


Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]


Example 2:

Input: l1 = [], l2 = []
Output: []


Example 3:

Input: l1 = [], l2 = [0]
Output: [0]


Link: topic link

answer:

# 一个详细的思路 --alex
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        #创建一个新的链表
        res = ListNode(0)
        #一个指针指向新的链表的头部
        c1 = res
        #开始比较L1和l2的值,只要有一个走完就停
        while(l1 and l2):
            #如果l1的值小于等于l2的值,则加入新的链表同时移动L1
            if l1.val<=l2.val:
                c1.next = ListNode(l1.val)
                l1 = l1.next
                c1 = c1.next
            #反之则添加l2的值,同时移动l2
            else l1.val>l2.val:
                c1.next = ListNode(l2.val)
                l2= l2.next
                c1 =c1.next
        #检查L1和l2哪个没走完,则将后面的直接加入新的链表即可
        if l1:
            c1.next = l1
        if l2:
            c1.next  = l2
        #返回头部的下一个即可
        return res.next

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if not l1 : return l2    #终止条件
        if not l2 : return l1
        if l1.val <= l2.val :    #递归条件
           return ListNode(l1.val, self.mergeTwoLists(l1.next, l2))
        else:
           return ListNode(l2.val, self.mergeTwoLists(l1, l2.next))

 

 

 

 

 

Guess you like

Origin blog.csdn.net/adminkeys/article/details/112598710