leetcode 2231.パリティによる桁スワップ後の最大数(python)

一緒に書く習慣を身につけましょう!「ナゲッツデイリーニュープラン・4月アップデートチャレンジ」に参加して12日目です。クリックしてイベントの詳細をご覧ください

説明

正の整数numが与えられます。同じパリティを持つnumの任意の2桁(つまり、両方の奇数桁または両方の偶数桁)を交換できます。

任意の数のスワップの後、numの可能な最大値を返します。

例1:

Input: num = 1234
Output: 3412
Explanation: Swap the digit 3 with the digit 1, this results in the number 3214.
Swap the digit 2 with the digit 4, this results in the number 3412.
Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.
Also note that we may not swap the digit 4 with the digit 1 since they are of different parities.
复制代码

例2:

Input: num = 65875
Output: 87655
Explanation: Swap the digit 8 with the digit 6, this results in the number 85675.
Swap the first digit 5 with the digit 7, this results in the number 87655.
Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.
复制代码

ノート:

1 <= num <= 10 ^ 9

解析

質問の意味に応じて、正の整数numを指定します。この質問では、numの任意の2桁の任意の2つの奇数または任意の2つの偶数を交換でき、数え切れないほど交換でき、最終的に可能なものを返します。変更後のnumの最大値。

競技中にこの質問を読んだとき、とてもシンプルだと思い、書いたコードは少し長めでした。いつもコードを最適化したかったのですが、イベントのために諦めました。臭くて長いです。 、彼らと私が同じレベルで書いたことを見つけただけで、コードを最適化するという欲求を即座に失いました。

実際、この質問では、主に基本的な操作と配列の単純な並べ替えについて説明します。考え方は非常に単純です。

  • 文字列はインデックス位置で変更できないため、numをlistnumに変更します
  • 偶数の偶数を取り出してAに入れ、Aを降順に並べ替えます
  • Aの要素を降順で配置してから、前の偶数の位置にnumで戻します。
  • 奇数の奇数を取り出してBに入れ、Bを降順に並べ替えます
  • Bの要素を降順で配置してから、前の奇数の位置にnumで戻します。
  • numsを文字列に連結して返します

時間計算量はO(N + NlogN)であり、空間計算量はO(N)です。

答え

class Solution(object):
    def largestInteger(self, num):
        """
        :type num: int
        :rtype: int
        """
        nums = list(str(num))
        N = len(nums)
        A = [i for i in nums if int(i)%2 == 0]
        A.sort()
        A = A[::-1]
        n = 0
        for i in range(N):
            if int(nums[i])%2 == 0:
                nums[i] = A[n]
                n += 1
        B = [i for i in nums if int(i)%2 == 1]
        B.sort()
        B = B[::-1]
        n = 0
        for i in range(N):
            if int(nums[i])%2 == 1:
                nums[i] = B[n]
                n += 1
        return int(''.join(nums))		
复制代码

運転結果

238 / 238 test cases passed.
Status: Accepted
Runtime: 34 ms
Memory Usage: 13.3 MB
复制代码

元のタイトルリンク

leetcode.com/contest/wee…

あなたのサポートは私の最大の動機です

おすすめ

転載: juejin.im/post/7085517090504835109