↓快轉到主要內容
  1. LeetCode/

LeetCode 2231: Largest Number After Digit Swaps by Parity

·1 分鐘· ·
LeetCode Easy Sorting Heap-Priority-Queue
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-11-22

  • 提交紀錄:Wrong Answer ×2 → Accepted

解題思路
#

「奇偶」指的是數字本身的奇偶,不是位置。把奇數位數和偶數位數分成兩組,各自由大到小排(或用 max-heap,Heap),再從左到右:原本是奇數的位置放奇數組最大的,偶數的位置放偶數組最大的。

我的嘗試
#

前兩版把分組的依據寫成 index 的奇偶(i % 2),不是數字本身的奇偶:5575 的四個位數都是奇數,可以排成 7555,這兩版一個沒回傳、一個回傳錯的結果。改成看 int(s) % 2 才 AC。

正確解法
#

class Solution:
    def largestInteger(self, num: int) -> int:
        digits = [int(c) for c in str(num)]
        odd = sorted((d for d in digits if d % 2), reverse=True)
        even = sorted((d for d in digits if d % 2 == 0), reverse=True)
        oi = ei = 0
        res = 0
        for d in digits:
            if d % 2:
                res = res * 10 + odd[oi]; oi += 1
            else:
                res = res * 10 + even[ei]; ei += 1
        return res

複雜度
#

時間 O(d log d)(d 是位數),空間 O(d)。

要特別避免的錯誤
#

  • 分組依據是數字的奇偶,不是 index 的奇偶。
  • 回傳整數。

面試口說整理
#

奇數只能跟奇數換、偶數只能跟偶數換,所以我把位數依奇偶分兩組各自由大到小排序,再從左到右,原本是奇數的位置放奇數組最大的,偶數的位置放偶數組最大的。

相關文章

LeetCode 2099: Find Subsequence of Length K With the Largest Sum
·1 分鐘
LeetCode Easy Array Hash-Table Sorting Heap-Priority-Queue
LeetCode 2099 解題筆記:選出最大的 k 個數(連同 index),再按 index 排回原本的順序
LeetCode 2335: Minimum Amount of Time to Fill Cups
·1 分鐘
LeetCode Easy Array Greedy Sorting Heap-Priority-Queue
LeetCode 2335 解題筆記:答案是 max(最多的那種, ceil(總數 / 2));模擬的話每秒從最多的兩種各裝一杯
LeetCode 1464: Maximum Product of Two Elements in an Array
·1 分鐘
LeetCode Easy Array Sorting Heap-Priority-Queue
LeetCode 1464 解題筆記:值都是正數,取最大的兩個數 a、b,答案是 (a - 1)(b - 1)
LeetCode 1337: The K Weakest Rows in a Matrix
·1 分鐘
LeetCode Easy Array Binary-Search Sorting Heap-Priority-Queue
LeetCode 1337 解題筆記:每列的士兵都在前面,用二分找第一個 0 就是士兵數;照(士兵數, 列號)排序取前 k 個
LeetCode 506: Relative Ranks
·1 分鐘
LeetCode Easy Array Sorting Heap-Priority-Queue
LeetCode 506 解題筆記:把 index 按分數由高到低排序,前三名給獎牌,其他給名次的字串,放回原本的位置
LeetCode 2357: Make Array Zero by Subtracting Equal Amounts
·1 分鐘
LeetCode Easy Array Hash-Table Greedy Sorting
LeetCode 2357 解題筆記:每次操作會讓最小的正數那一群變成 0,所以次數就是不同的正數有幾種