「这是我参与2022首次更文挑战的第32天,活动详情查看:2022首次更文挑战」
比较版本号 Compare Version Numbers
LeetCode传送门165. 比较版本号
题目
给你两个版本号 version1 和 version2 ,请你比较它们。
版本号由一个或多个修订号组成,各修订号由一个 '.' 连接。每个修订号由 多位数字 组成,可能包含 前导零 。每个版本号至少包含一个字符。修订号从左到右编号,下标从 0 开始,最左边的修订号下标为 0 ,下一个修订号下标为 1 ,以此类推。例如,2.5.33 和 0.1 都是有效的版本号。
比较版本号时,请按从左到右的顺序依次比较它们的修订号。比较修订号时,只需比较 忽略任何前导零后的整数值 。也就是说,修订号 1 和修订号 001 相等 。如果版本号没有指定某个下标处的修订号,则该修订号视为 0 。例如,版本 1.0 小于版本 1.1 ,因为它们下标为 0 的修订号相同,而下标为 1 的修订号分别为 0 和 1 ,0 < 1 。
返回规则如下:
- 如果 version1 > version2 返回 1,
- 如果 version1 < version2 返回 -1,
- 除此之外返回 0。
Given two version numbers, version1 and version2, compare them.
Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers.
To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1.
Return the following:
- If version1 < version2, return -1.
- If version1 > version2, return 1.
- Otherwise, return 0.
Example:
Input: version1 = "1.01", version2 = "1.001"
Output: 0
Explanation: Ignoring leading zeroes, both "01" and "001" represent the same integer "1".
Input: version1 = "1.0", version2 = "1.0.0"
Output: 0
Explanation: version1 does not specify revision 2, which means it is treated as "0".
Input: version1 = "0.1", version2 = "1.1"
Output: -1
Explanation: version1's revision 0 is "0", while version2's revision 0 is "1". 0 < 1, so version1 < version2.
Constraints:
- 1 <= version1.length, version2.length <= 500
- version1 and version2 only contain digits and '.'.
- version1 and version2 are valid version numbers.
- All the given revisions in version1 and version2 can be stored in a 32-bit integer.
思考线
解题思路
由于版本号是以.分隔的字符串,所以我们先用split方法把字符串转换为数组,同时把分隔的字符串变为数字进行比较。
在这里我们要注意,两个version转化后的数组可能长度不一致,我们找到长度最大的数组,并进行遍历。按顺序比较两个version的大小即可。同时,在比较时,可能出现值不存在的情况,这个时候我们要补上0
function compareVersion(version1: string, version2: string): number {
const v1 = version1.split('.').map(item => Number(item))
const v2 = version2.split('.').map(item => Number(item))
const len = Math.max(v1.length, v2.length)
for (let i = 0; i < len; i++) {
const a = v1[i] ? v1[i] : 0;
const b = v2[i] ? v2[i] : 0;
if (a > b) return 1
if (b > a) return -1
}
return 0
};
时间复杂度
O(n):n为比较长的版本的长度
这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。