165. Compare Version Numbers

Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.

You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.

Here is an example of version numbers ordering:

0.1 < 1.1 < 1.2 < 13.37

这道题主要是要考虑好多种情况比如1和1.0,1.0和1.0.1之类的,还有1.1和1.1.0.0.0.0.1:

var compareVersion = function(version1, version2) {
    var a = version1.split(".");
    var b = version2.split(".");
    var ai = 0;
    var bi = 0;
    var an = a.length;
    var bn = b.length;
    while (aiparseInt(b[bi]))
            return 1;
        ai++;
        bi++;
    }
    if (ai===an&&bi===bn)
        return 0;
    if (ai===an) {
        while (bi

嗯,还有一种简单的方法,但是需要两个额外的变量:

var compareVersion = function(version1, version2) {
    var a = version1.split(".");
    var b = version2.split(".");
    var ai = 0;
    var bi = 0;
    var an = a.length;
    var bn = b.length;
    var result1 = 0;
    var result2 = 0;
    while (airesult2) return 1;
    }
    return 0;
};

这两个方法时间复杂度是一样的,都要遍历两个字符串。

你可能感兴趣的:(165. Compare Version Numbers)