iT邦幫忙

2024 iThome 鐵人賽

DAY 3
1

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” – Martin Fowler, software engineer, object-oriented programming pioneer

1768. Merge Strings Alternately

通常,我們會結合題目與 Example 一起看,會更方便理解這個題目的意思。

題目描述:

You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.

Return the merged string.

Example 1:

Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1:  a   b   c
word2:    p   q   r
merged: a p b q c r

首先,看到這個題目後,你的第一個念頭就是把 word1 與 word2 輪流拿一個元素出來放到新的字串上,然後將該字串回傳,這是一個好的想法,我們現在的目標就是要把這件對人類來說很簡單的事情,把它拆分成不同的步驟交給程式執行,並且考慮到可能的問題

你的第一個版本可能會長這樣:

class Solution(object):
    def mergeAlternately(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: str
        """
        result = ""
        for i in range(0, len(word1)):
            result += word1[i]
            result += word2[i]
        
        return result

想像一下,這會遇到什麼問題?

題目中沒有說 word1 和 word2 的長度一定相同,所以如果 word1 比 word2 的長度短,那麼 word2 就會有後面一截沒有放到 result 裡面,如果 word1 比 word2 的長度長,那麼也會導致 word2[i] 在 i 跑到比word2的長度還長的時候,遇到越界問題

讓我們先確定好需要遍歷的次數,以及需要遍歷的範圍:

遍歷的次數只需要一次就好,遍歷的範圍至少要是 word1 與 word2 兩者之間最長的字串,這樣才能確保每個元素都有被新增到,再來就是如果越界了,那就不做處理,第二版如下:

# 也可以只取較短的,然後在迴圈結束後再把較長的字串後面給補上!
class Solution(object):
    def mergeAlternately(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: str
        """
        result = ""
        n1 = len(word1)
        n2 = len(word2)
        n = max(n1, n2)
        for i in range(0, n):
            if (i < n1):
                result += word1[i]
            if (i < n2):
                result += word2[i]
        
        return result

1431. Kids With the Greatest Number of Candies

題目描述:

There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have.

Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise.

Note that multiple kids can have the greatest number of candies.

Example 1:

Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true]
Explanation: If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.

先分析題目:

首先,題目要的是原本candies陣列裡面最多的candy,而不是給完extraCandies還要去找一遍,所以我們可以先把取出maxCandy的動作放在迴圈之前,然後迴圈裡面再把 candies[i] + extraCandies 與maxCandy 做比較:

class Solution(object):
    def kidsWithCandies(self, candies, extraCandies):
        """
        :type candies: List[int]
        :type extraCandies: int
        :rtype: List[bool]
        """
        result = []
        maxCandy = max(candies)
        for i in range(0, len(candies)):
            if candies[i] + extraCandies >= maxCandy:
                result.append(True)
            else:
                result.append(False)
        
        return result
        
# 簡化版
class Solution(object):
    def kidsWithCandies(self, candies, extraCandies):
        big = max(candies)
        res = [candy + extraCandies >= big for candy in candies]
        return res

有時候簡化版的程式可讀性會更好或更差,對於程式開發來說,可讀性=維護性,寫出一目瞭然的程式是很重要的!


上一篇
Day2 演算法(0) 介紹
下一篇
Day4 演算法(2) 二分搜尋法(Binary Search)與貪心法(Greedy)
系列文
什麼都摸一點!拒絕當不沾鍋!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言