“This is the 20th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
Hope is a good thing, maybe the best of things. And no good thing ever dies.
The title
A version number consists of one or more revision numbers, each connected by a.. Each revision number consists of multiple digits that may contain leading zeros. Each version number contains at least one character. Revision numbers are numbered from left to right, with subscripts 0, the leftmost revision number subscript 0, the next revision number subscript 1, and so on. For example, 2.5.33 and 0.1 are valid version numbers.
The return rule is as follows:
Return 1 if version1 > version2, -1 if version1 < version2, and 0 otherwise.
Example 1: Input: version1 = "1.01", version2 = "1.001" Output: 0 Explanation: Ignore leading zeros, "01" and "001" both represent the same integer "1" Example 2: Input: Version1 = "1.0", version2 = "1.0.0" Output: 0 Explanation: version1 does not specify a revision number with subscript 2, which is regarded as "0" Example 3: Input: Version1 = "0.1", version2 = "1.1" Output: -1 Description: In version1, the revision number with subscript 0 is "0"; in version2, the revision number with subscript 0 is "1". 0 < 1, so version1 < version2 Example 4: Input: version1 = "1.0.1", version2 = "1" Output: 1 Version1 = "7.5.2.4", version2 = "7.5.3" Output: -1Copy the code
Thought analysis
When comparing version numbers, compare their revision numbers from left to right. When comparing revision numbers, only the integer values after ignoring any leading zeros are compared. That is, revision number 1 is equal to revision number 001. If the version number does not specify a revision number at a subscript, the revision number is treated as 0. For example, version 1.0 is less than version 1.1 because they have the same revision number with subscript 0, and the revision number with subscript 1 is 0 and 1, respectively, with 0 < 1.
The problem solving
/** * @param {string} version1 * @param {string} version2 * @return {number} */ var compareVersion = function(version1, Version2) {const arr1 = version1.split('.') const arr2 = version2.split('.') // Compare the length of two arrays, Const maxLength = math.max (arr1.length, arr2.length); For (let I = 0; i<maxLength; I++) {/ / in turn from left to right to compare version number const a = arr1 [I] | | 0; const b = arr2[i] || 0; If (Number(a) > Number(b)) {return 1} else if(Number(a) < Number(b)) {return -1} If (I === maxLength - 1) {return 0}}};Copy the code
The execution result
Add: leetcode-cn.com/problems/co…
conclusion
If this article helped you, please like 👍 and follow ⭐️.
If there are any errors in this article, please correct them in the comments section 🙏🙏
Welcome to pay attention to my wechat public number, exchange technology together, wechat search 🔍 : “fifty years later”