当前位置:网站首页>Brush question 4

Brush question 4

2022-07-07 23:05:00 Anny Linlin

10、 Given an include n Array of integers nums and A target value target. find nums Three integers in , Make their sum and target Nearest . Returns the sum of the three numbers . Assume that there is only one answer for each group of input .

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        min = sum(nums[0:3])
        for i in range(len(nums) - 2):
            left, right = i + 1, len(nums) - 1
            while left < right:
                sum = nums[i] + nums[left] + nums[right]
                min = min if abs(min - target) < abs(sum - target) else sum
                if  sum == target:
                    return sum
                elif sum > target:
                    right -= 1
                else:
                    left += 1
        return min

11、 Valid parenthesis

Given one only includes '(',')','{','}','[',']' String , Determines whether the string is valid .

Valid string needs to meet :

  • Opening parentheses must be closed with closing parentheses of the same type .

  • The left parenthesis must be closed in the correct order .

Note that an empty string can be considered a valid string .

def isValid(s):
    if s and len(s) % 2 is 0:
        a = {')': '(', ']': '[', '}': '{'}
        l = [None]
        for i in s:
            if i in a and a[i] == l[-1]:
                l.pop()
            else:
                l.append(i)
        return len(l) == 1
    elif len(s) % 2 is 1:
        return False
    else:
        return True

12、 Merge two sequential tables

Merge two ordered lists into a new ordered list and return . The new linked list is made up of all the nodes of the given two linked lists .

Example :

Input :1->2->4, 1->3->4

Output :1->1->2->3->4->4

class Solution:
    def mergeTwoLists(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
        head = ListNode(0)
        node = head
        while l1 and l2:
            if l1.val <= l2.val:
                node.next = l1
                l1 = l1.next
            else:
                node.next = l2
                l2 = l2.next
            node = node.next
        if l1:
            node.next = l1
        if l2:
            node.next = l2
        return head.next

原网站

版权声明
本文为[Anny Linlin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130601098495.html