问题描述
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.
Example 1:
Input: version1 = “0.1”, version2 = “1.1”
Output: -1
Example 2:
Input: version1 = “1.0.1”, version2 = “1”
Output: 1
Example 3:
Input: version1 = “7.5.2.4”, version2 = “7.5.3”
Output: -1
思路分析
给两个string代表的版本号,计算那个版本更大,返回相应的int值。
一开始以为版本号都是个位的,然后被上了一课。所以需要每次解析出‘.’之间的数字,然后进行比较。如果有哪个string长度不足了,那么下一个就时0,必然会小。如果两个string长度相同,完成了while循环,那么一定是一样长的。
代码
class Solution {
public:
int compareVersion(string version1, string version2) {
int i = 0, j = 0, num1 = 0, num2 = 0;
int l1 = version1.length(), l2 = version2.length();
while(i < l1 || j < l2){
while(i < l1 && version1[i] != '.'){
num1 = 10 * num1 + (version1[i] - '0');
i++;
}
while(j < l2 && version2[j] != '.'){
num2 = 10 * num2 + (version2[j] - '0');
j++;
}
if(num1 < num2)
return -1;
else if(num1 > num2)
return 1;
num1 = 0;
num2 = 0;
i++;
j++;
}
return 0;
}
};
时间复杂度:
O(min(m,n))
O
(
m
i
n
(
m
,
n
)
)
//list中int的个数
空间复杂度:
O(1)
O
(
1
)
反思
被”01”“1”的case卡了一下,在while内的训话就是判断1和-1的,所以可能出现num1 == num2的情况,需要再else if判读一下。