zeqing-guo / algorithms-study

MIT License
0 stars 1 forks source link

Leetcode-13: Roman to Integer #83

Open zeqing-guo opened 8 years ago

zeqing-guo commented 8 years ago

Description

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

My Solution

代码的run time是6ms (97.91%),时间复杂度是O(n),空间复杂度是O(1)

public class Solution {
    public int romanToInt(String s) {
        int[] map = new int[26];
        map['I' - 'A'] = 1;
        map['V' - 'A'] = 5;
        map['X' - 'A'] = 10;
        map['L' - 'A'] = 50;
        map['C' - 'A'] = 100;
        map['D' - 'A'] = 500;
        map['M' - 'A'] = 1000;

        char[] rChar = s.toCharArray();
        int len = rChar.length;
        int sum = 0;
        if (len == 0) {
            return 0;
        }

        int prev = map[rChar[0] - 'A'];
        int curr = 0;

        for (int i = 1; i < len; ++i) {
            curr = map[rChar[i] - 'A'];
            if (curr > prev) {
                sum -= prev;
            } else {
                sum += prev;
            }
            prev = curr;
        }
        sum += prev;
        return sum;
    }

}

Analysis

水题,发现map用array比用hashmap快好多。

kernelzeroday commented 8 months ago

somebody spamming ur shit pretending to be github sending fake job offers with a token grabber, fyi look out anyone that gets a weird email claiming to be offering a job and sending a click here link

kernelzeroday commented 8 months ago

@Drewsapple, @sclarke001, @JonathanAmenechi, @mmyyrroonn, @hussein-aitlahcen, @mmatila, @0xca11, @aroralanuk, @emilamaj, @iamazy, @kernelzeroday, @royswale, @d4rm5, @Dadybayo, @oooo723, @grantkee, @austbot, @0xStrobe, @bmgalego

don't click the link