iT邦幫忙

0

leetcode 365天 #Day109

  • 分享至 

  • xImage
  •  

本人快速地發呆的過程~
Yes


  1. Determine if String Halves Are Alike (easy)
    https://leetcode.com/problems/determine-if-string-halves-are-alike/
    Submission:https://leetcode.com/submissions/detail/853064886/

You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.
Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters.
Return true if a and b are alike. Otherwise, return false.
簡單來說,將字串s分開成前後兩段,檢查前後兩段的母音個數是否相同

class Solution:
    #把字串切兩半,只要有相同個數的母音,即True,否則False
    def halvesAreAlike(self, s: str) -> bool:
        sL = len(s)
        vowels = "aeiouAEIOU"
        a,b = s[:sL//2],s[sL//2:]
        # aC,bC = len([i for i in a if i in vowels]),len([i for i in b if i in vowels])
        aC,bC = 0,0
        for i in range(len(a)):
            if a[i] in vowels:
                aC += 1
            if b[i] in vowels:
                bC += 1
        return aC == bC

  1. Two Sum Less Than K (easy)
    https://leetcode.com/problems/two-sum-less-than-k/
    Submission:https://leetcode.com/submissions/detail/853068758/
    Given an array nums of integers and integer k, return the maximum sum such that there exists i < j with nums[i] + nums[j] = sum and sum < k. If no i, j exist satisfying this equation, return -1.
    在nums裡面找到兩個值,加起來要比k小,然後找出比k小的最大值多少。
    這題做法可以有很多種看要不要先sort
class Solution:#不sort
    兩個數字相加,找出小於K的最大值
    def twoSumLessThanK(self, nums: List[int], k: int) -> int:
        ans = 0
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                temp = nums[i] + nums[j]
                if temp < k and temp > ans:
                    ans = temp
        if ans == 0:
            return -1
        return ans
class Solution:#sort的方法
    #先整理後,一個由前往後,一個由後往前
    #剛好到小於k的點的時候就可以比大小
    def twoSumLessThanK(self, nums: List[int], k: int) -> int:
        ans = 0
        nums.sort()
        for i in range(len(nums)):
            for j in range(len(nums)-1,i,-1):
                temp = nums[i] + nums[j]
                if temp < k:
                    ans = max(temp,ans)
                    break
        if ans == 0:
            return -1
        return ans
    
    #Binary Search
    def twoSumLessThanK(self, nums: List[int], k: int) -> int:
        def bSearch(nums,target):
            L,R = 0,len(nums)-1
            while L < R:
                M = (L+R)//2
                if nums[M] > target:
                    R = M
                else:
                    L = M + 1
            return L-1
        ans = 0
        nums.sort()
        for i in range(len(nums)):
            j = bSearch(nums,k-nums[i])
            temp = nums[i]+nums[j]
            if i!=j and temp < k:
                ans = max(ans,temp)
        if ans == 0:
            return -1
        return ans

  1. Minimize Product Sum of Two Arrays
    https://leetcode.com/problems/minimize-product-sum-of-two-arrays/
    Submission:https://leetcode.com/submissions/detail/853079625/

The product sum of two equal-length arrays a and b is equal to the sum of a[i] * b[i] for all 0 <= i < a.length (0-indexed).

For example, if a = [1,2,3,4] and b = [5,2,3,1], the product sum would be 15 + 22 + 33 + 41 = 22.
Given two arrays nums1 and nums2 of length n, return the minimum product sum if you are allowed to rearrange the order of the elements in nums1.
給予2個數列,要找出一種方式,把兩個數列的每一個值進行互乘之後找到最小值。
原則上不難,就是要有數學概念,小的對大的,大的對小的就可以解出來了。

class Solution:
    #找到最小的nums1[i]*nums2[i]總和
    def minProductSum(self, nums1: List[int], nums2: List[int]) -> int:
        nums1.sort()
        nums2.sort(reverse = True)
        ans = 0
        for i in range(len(nums1)):
            ans += nums1[i]*nums2[i]
        return ans

  1. Populating Next Right Pointers in Each Node
    https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
    Submission:https://leetcode.com/submissions/detail/853089544/
    You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:

struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

這題個人買喜歡的,就是考驗你的基本功,對於tree到底了不了解,對於tree+level order traversal到底熟不熟。

"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""
#一開始的寫法
class Solution:
    #perfect binary tree
    #想睡覺了,寫起來都怪怪的
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
        if root is None:
            return None
        nodeList = [0]
        tempList = [2**i for i in range(12)]
        tempList2 = [tempList[0]]
        for i in range(1,len(tempList)):
            tempList2.append(tempList2[-1] + tempList[i])
        # print(tempList2)
        def bfs(root):
            queue = [root]
            while queue:
                temp = queue.pop(0)
                if temp != None:
                    nodeList.append(temp)
                    queue.append(temp.left)
                    queue.append(temp.right)
        bfs(root)
        # for i in nodeList:
        #     print(i.val,end = " ")
        for i in range(1,len(nodeList)):
            if i in tempList2:
                nodeList[i].next = None
            else:
                nodeList[i].next = nodeList[i+1]
        return root
"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""
#參考別人的寫法
class Solution:
    #參考別人的寫法
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
        if not root:
            return root
        curr = root
        while curr:
            nex = curr.left #先往左
            while curr and curr.left:#因為左會是頭,所以檢查左在不在即可
                #curr會是left跟right的parent,很像廢話的重點
                curr.left.next = curr.right
                if curr.next:#如果parent有next,則child的right必有next
                    curr.right.next = curr.next.left 
                else:#反之則為None
                    curr.right.next = None
                curr = curr.next#一層一層來
            curr = nex#往下一層
        return root

以上是今天的練習感謝大家,還迎大家找我聊天喔~QQ


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言