阅读 140

LeetCode第11天🐱‍🏍

165. 比较版本号

切割版本号进行比较

var compareVersion = function(version1, version2) {
    let cut1 = version1.split('.'),
        cut2 = version2.split('.')
    for (let i = 0; i < Math.max(cut1.length, cut2.length); i++) {
        if (!cut1[i]) {
            cut1[i] = 0
        }
        if (!cut2[i]) {
            cut2[i] = 0
        }
        if (Number(cut1[i]) < cut2[i]) {
            return -1
        }
        if (Number(cut1[i]) > cut2[i]) {
            return 1
        }
    }
    return 0
};
复制代码

优化空间复杂度

var compareVersion = function(version1, version2) {
    const n = version1.length, m = version2.length;
    let i = 0, j = 0;
    while (i < n || j < m) {
        let x = 0;
        for (; i < n && version1[i] !== '.'; ++i) {
            x = x * 10 + version1[i].charCodeAt() - '0'.charCodeAt();
        }
        ++i; // 跳过点号
        let y = 0;
        for (; j < m && version2[j] !== '.'; ++j) {
            y = y * 10 + version2[j].charCodeAt() - '0'.charCodeAt();
        }
        ++j; // 跳过点号
        if (x !== y) {
            return x > y ? 1 : -1;
        }
    }
    return 0;
};
复制代码
文章分类
前端