Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 12 · Sorting + Simple Greedy

Integer to Roman

LeetCode 12 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Greedy over values including subtractive pairs.

ಮಧ್ಯಮHash TableMathString
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Integer to Roman (LeetCode 12) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Sorting + Simple Greedy ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Roman numerals are greedy: always write the largest symbol that still fits. Including the six subtractive pairs (CM, CD, XC, XL, IX, IV) in the table makes the greedy rule produce the correct form.

Approach

  1. 1

    Table of 13 values from 1000 down to 1.

  2. 2

    While num > 0, append each symbol as many times as it fits.

  3. 3

    Subtract its value each time.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Greedy tablePythonO(1) time
class Solution:
    def intToRoman(self, num: int) -> str:
        nums = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
        symbols = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
        ans = ""
        while num>0:
            for index,cur_num in enumerate(nums):
                while cur_num<=num:
                    ans+=symbols[index]
                    num=num-cur_num
                    if cur_num>num:
                        break;
        return ans
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Integer to Roman — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Integer to Roman ಹಿಂದಿನ intuition ಏನು?

Roman numerals are greedy: always write the largest symbol that still fits. Including the six subtractive pairs (CM, CD, XC, XL, IX, IV) in the table makes the greedy rule produce the correct form.

Integer to Roman (LeetCode 12) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Table of 13 values from 1000 down to 1. 2. While num > 0, append each symbol as many times as it fits. 3. Subtract its value each time.

Integer to Roman ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(1). Space: O(1). (Accepted approach: Greedy table.)

Integer to Roman ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Without CM, XC, IV, etc. you'd produce 'VIIII'.