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 (ai<an&&bi<bn) {
if (parseInt(a[ai])<parseInt(b[bi]))
return -1;
else if (parseInt(a[ai])>parseInt(b[bi]))
return 1;
ai++;
bi++;
}
if (ai===an&&bi===bn)
return 0;
if (ai===an) {
while (bi<bn) {
if (parseInt(b[bi])!==0)
return -1;
bi++;
}
return 0;
}
if (bi===bn) {
while (ai<an) {
if (parseInt(a[ai])!==0)
return 1;
ai++;
}
return 0;
}
};
嗯,还有一种简单的方法,但是需要两个额外的变量:
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 (ai<an||bi<bn) {
if(ai<an) result1 += parseInt(a[ai++]);
if(bi<bn) result2 += parseInt(b[bi++]);
if (result1<result2) return -1;
if (result1>result2) return 1;
}
return 0;
};
这两个方法时间复杂度是一样的,都要遍历两个字符串。