天天看點

Leetcode騰訊精選練習50 -- 16、20、21

```cpp
題号:16
難度:中等
https://leetcode-cn.com/problems/3sum-closest/
           
```python
class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums = sorted(nums)
        result = nums[0] + nums[1] + nums[2]
        for i in range(0, len(nums) - 2):
            start = i + 1
            end = len(nums) - 1
            while start < end:
                sum = nums[start] + nums[end] + nums[i]
                if abs(target - sum) < abs(target - result):
                    result = sum
                if sum > target:
                    end -= 1
                elif sum < target:
                    start += 1
                else:
                    return result
        return result
           
題号:20
難度:簡單
https://leetcode-cn.com/problems/valid-parentheses/ 
           
class Solution:
    def isValid(self, s: str) -> bool:
        dic = {")": "(", "}": "{", "]": "["}
        if s is None:
            return True
            
        count = len(s)
        if count % 2 == 1:
            return False
            
        lst = list()
        for i in range(count):
            c = s[i]
            if len(lst) == 0:
                lst.append(c)
            elif c == "[" or c == "{" or c == "(":
                lst.append(c)
            elif lst[-1] == dic[c]:
                lst.pop()
            else:
                return False
        return len(lst) == 0
        
           
題号:21
難度:簡單
https://leetcode-cn.com/problems/merge-two-sorted-lists/
           
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        pHead = ListNode(None)
        temp = pHead
        while(l1 and l2):
            if (l1.val <= l2.val):
                temp.next = l1                
                l1 = l1.next
            else :
                temp.next = l2
                l2 = l2.next
            temp = temp.next
             
        if l1 is not None:
            temp.next = l1 
        else :
            temp.next = l2
           

繼續閱讀