zoukankan      html  css  js  c++  java
  • lc0316

    ✅ 13. 罗马数字转整数

    https://leetcode-cn.com/problems/roman-to-integer/

    描述

    罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
    
    字符          数值
    I             1
    V             5
    X             10
    L             50
    C             100
    D             500
    M             1000
    例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。
     27 写做  XXVII, 即为 XX + V + II 。
    
    通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。
    
    这个特殊的规则只适用于 以下六种 情况:
    
    I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
    X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 
    C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
    给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。
    
    示例 1:
    
    输入: "III"
    输出: 3
    示例 2:
    
    输入: "IV"
    输出: 4
    示例 3:
    
    输入: "IX"
    输出: 9
    
    

    解答

    c todo watch me

    fu-Z2aABL1fkT福
    1 年前
    #define nI 1  //直接用define I 1,好像会有歧义
    #define nV 5 
    #define nX 10
    #define nL 50
    #define nC 100
    #define nD 500
    #define nM 1000
    
    int romanToInt(char* s) 
    { 
        int num = 0, flag = 0;   /*立一个flag,是因为之前我在后面会用三个if,一个else,其实我的初衷是三个if有其中任何一个满足都不要再执行else了
                                 但是如果没有flag的话,意思是第三个if如果不成立便会跳去else,比如IV,第一个if满足,然后第三个if不满足,else这时候
                                 就会出来执行,很不爽*/
        while(*s != NULL)
        {
            if(*s == 'I' && (*(s + 1) == 'V' || *(s + 1) == 'X'))     //接下来的这三个if都有特殊含义,所以flag=1,普通情况属于flag=0
            {
                flag = 1;
                switch(*(s + 1))
                {
                    case 'V':num += (nV - nI); s+=2; break;
                    case 'X':num += (nX - nI); s+=2; break;
                }
            }
            if(*s == 'X' && (*(s + 1) == 'L' || *(s + 1) == 'C'))
            {
                flag = 1;
                switch(*(s + 1))
                {
                    case 'L':num += (nL - nX); s+=2; break;
                    case 'C':num += (nC - nX); s+=2; break;
                }
            }
            if(*s == 'C' && (*(s + 1) == 'D' || *(s + 1) == 'M'))
            {
                flag = 1;
                switch(*(s + 1))
                {
                    case 'D':num += (nD - nC); s+=2; break;
                    case 'M':num += (nM - nC); s+=2; break;
                }
            }
            if(flag == 0)   //本来这里是else的,改为if(flag == 0)
            {
                switch(*s)
                {
                    case 'I':num += nI; s += 1; break;
                    case 'V':num += nV; s += 1; break;
                    case 'X':num += nX; s += 1; break;
                    case 'L':num += nL; s += 1; break;
                    case 'C':num += nC; s += 1; break;
                    case 'D':num += nD; s += 1; break;
                    case 'M':num += nM; s += 1; break;
                }
            }
            flag = 0;  //最后置回普通状态
        }
        return num;
    }
    

    py

    class Solution:
        def romanToInt(self, s: str) -> int:
            my_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 
            'D': 500, 'M': 1000}# tt 我们能换行吗?在{} 中换行。;;可以
            ans = 0
            for i in len(s):
                if (i < len(s) - 1) and (my_dict[s[i]] < my_dict[s[i+1]]):
                    ans -= my_dict[s[i]]
                else:
                    ans += my_dict[s[i]]
            return ans
    # fixed mine: watch tt47
    class Solution:
        def romanToInt(self, s: str) -> int:
            my_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 
            'D': 500, 'M': 1000}# tt 我们能换行吗?在{} 中换行。
            ans = 0
            for i in range(len(s)):# tt47 必须使用range!!!
                if (i < len(s) - 1) and (my_dict[s[i]] < my_dict[s[i+1]]):
                    ans -= my_dict[s[i]]
                else:
                    ans += my_dict[s[i]]
            return ans
    '''
    执行用时 :
    52 ms
    , 在所有 Python3 提交中击败了
    73.58%
    的用户
    内存消耗 :
    13.6 MB
    , 在所有 Python3 提交中击败了
    5.12%
    的用户
    '''
    

    ✅ 1114. 按序打印

    https://leetcode-cn.com/problems/print-in-order/

    描述

    我们提供了一个类:
    
    public class Foo {
      public void one() { print("one"); }
      public void two() { print("two"); }
      public void three() { print("three"); }
    }
    三个不同的线程将会共用一个 Foo 实例。
    
    线程 A 将会调用 one() 方法
    线程 B 将会调用 two() 方法
    线程 C 将会调用 three() 方法
    请设计修改程序,以确保 two() 方法在 one() 方法之后被执行,three() 方法在 two() 方法之后被执行。
    
     
    
    示例 1:
    
    输入: [1,2,3]
    输出: "onetwothree"
    解释: 
    有三个线程会被异步启动。
    输入 [1,2,3] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 two() 方法,线程 C 将会调用 three() 方法。
    正确的输出是 "onetwothree"。
    示例 2:
    
    输入: [1,3,2]
    输出: "onetwothree"
    解释: 
    输入 [1,3,2] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 three() 方法,线程 C 将会调用 two() 方法。
    正确的输出是 "onetwothree"。
     
    
    注意:
    
    尽管输入中的数字似乎暗示了顺序,但是我们并不保证线程在操作系统中的调度顺序。
    
    你看到的输入格式主要是为了确保测试的全面性。
    
    

    解答

    没有头绪。

    官方解答: 是看编程语言的各类 锁 啊:

    依赖关系可以通过并发机制实现。使用一个共享变量 firstJobDone 协调第一个方法与第二个方法的执行顺序,使用另一个共享变量 secondJobDone 协调第二个方法与第三个方法的执行顺序。

    算法

    首先初始化共享变量 firstJobDone 和 secondJobDone,初始值表示所有方法未执行。

    方法 first() 没有依赖关系,可以直接执行。在方法最后更新变量 firstJobDone 表示该方法执行完成。

    方法 second() 中,检查 firstJobDone 的状态。如果未更新则进入等待状态,否则执行方法 second()。在方法末尾,更新变量 secondJobDone 表示方法 second() 执行完成。

    方法 third() 中,检查 secondJobDone 的状态。与方法 second() 类似,执行 third() 之前,需要先等待 secondJobDone 的状态。

    上述算法的实现在很大程度上取决于选择的编程语言。尽管在 Java,C++ 和 Python 中都存在互斥与信号量,但不同语言对并发机制有不同实现。

    c++ 的 semaphore lib

    #include <semaphore.h>
    
    class Foo {
    
    protected:
        sem_t firstJobDone;
        sem_t secondJobDone;
    
    public:
    
        Foo() {
            sem_init(&firstJobDone, 0, 0);
            sem_init(&secondJobDone, 0, 0);
        }
    
        void first(function<void()> printFirst) {
            // printFirst() outputs "first".
            printFirst();
            sem_post(&firstJobDone);
        }
    
        void second(function<void()> printSecond) {
            sem_wait(&firstJobDone);
            // printSecond() outputs "second".
            printSecond();
            sem_post(&secondJobDone);
            
        }
    
        void third(function<void()> printThird) {
            sem_wait(&secondJobDone);
            // printThird() outputs "third".
            printThird();
        }
    };
    
    

    py 博君一笑

    来来来睡眠大法
    
    import time
    class Foo:
        def __init__(self):
            pass
    
    
        def first(self, printFirst: 'Callable[[], None]') -> None:
            
            # printFirst() outputs "first". Do not change or remove this line.
            
            printFirst()
    
    
        def second(self, printSecond: 'Callable[[], None]') -> None:
            
            # printSecond() outputs "second". Do not change or remove this line.
            time.sleep(0.01)
            printSecond()
    
    
        def third(self, printThird: 'Callable[[], None]') -> None:
            
            # printThird() outputs "third". Do not change or remove this line.
            time.sleep(0.02)
            printThird()
    

    py: thread lock api

    from threading import Lock
    
    class Foo:
        def __init__(self):
            self.firstJobDone = Lock()
            self.secondJobDone = Lock()
            self.firstJobDone.acquire()
            self.secondJobDone.acquire()
    
        def first(self, printFirst: 'Callable[[], None]') -> None:
            # printFirst() outputs "first".
            printFirst()
            # Notify the thread that is waiting for the first job to be done.
            self.firstJobDone.release()
    
        def second(self, printSecond: 'Callable[[], None]') -> None:
            # Wait for the first job to be done
            with self.firstJobDone:
                # printSecond() outputs "second".
                printSecond()
                # Notify the thread that is waiting for the second job to be done.
                self.secondJobDone.release()
    
        def third(self, printThird: 'Callable[[], None]') -> None:
    
            # Wait for the second job to be done.
            with self.secondJobDone:
                # printThird() outputs "third".
                printThird()
    '''
    执行用时 :
    52 ms
    , 在所有 Python3 提交中击败了
    44.52%
    的用户
    内存消耗 :
    13.8 MB
    , 在所有 Python3 提交中击败了
    5.06%
    的用户
    '''
    

    java 用原子类型

    class Foo {
    
      private AtomicInteger firstJobDone = new AtomicInteger(0);
      private AtomicInteger secondJobDone = new AtomicInteger(0);
    
      public Foo() {}
    
      public void first(Runnable printFirst) throws InterruptedException {
        // printFirst.run() outputs "first".
        printFirst.run();
        // mark the first job as done, by increasing its count.
        firstJobDone.incrementAndGet();
      }
    
      public void second(Runnable printSecond) throws InterruptedException {
        while (firstJobDone.get() != 1) {
          // waiting for the first job to be done.
        }
        // printSecond.run() outputs "second".
        printSecond.run();
        // mark the second as done, by increasing its count.
        secondJobDone.incrementAndGet();
      }
    
      public void third(Runnable printThird) throws InterruptedException {
        while (secondJobDone.get() != 1) {
          // waiting for the second job to be done.
        }
        // printThird.run() outputs "third".
        printThird.run();
      }
    }
    
    
    

    Java 用信号量 api

    import java.util.concurrent.Semaphore;
    class Foo {
        public Semaphore seam_first_two = new Semaphore(0);
        
        public Semaphore seam_two_second = new Semaphore(0);
        
        public Foo() {
            
        }
    
        public void first(Runnable printFirst) throws InterruptedException {
            printFirst.run();
            seam_first_two.release();
        }
    
        public void second(Runnable printSecond) throws InterruptedException {
            seam_first_two.acquire();
            printSecond.run();
            seam_two_second.release();
        }
    
        public void third(Runnable printThird) throws InterruptedException {
            seam_two_second.acquire();
            printThird.run();
        }
    }
    
  • 相关阅读:
    switch_goto
    隐藏 窗口的整个 标题栏(包括右上角的关闭)
    asp的邦定表达式异常 <_ %_ = strParentid _%_>不能传到下个页面
    【收藏】default.rdp配置
    计算机网络中的性能指标
    当某个快捷键不能用时很可能是热键冲突
    java的FOR循环 打印三角形
    二进制 八进制 十进制 十六进制
    linux的vim编辑命令常用
    JIRA的备份
  • 原文地址:https://www.cnblogs.com/paulkg12/p/12503521.html
Copyright © 2011-2022 走看看