|
| 1 | +/* |
| 2 | +165. Compare Version Numbers |
| 3 | +https://leetcode.com/problems/compare-version-numbers/ |
| 4 | +
|
| 5 | +Compare two version numbers version1 and version2. |
| 6 | +If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0. |
| 7 | +
|
| 8 | +You may assume that the version strings are non-empty and contain only digits and the . character. |
| 9 | +
|
| 10 | +The . character does not represent a decimal point and is used to separate number sequences. |
| 11 | +
|
| 12 | +For instance, 2.5 is not "two and a half" or "half way to version three", |
| 13 | +it is the fifth second-level revision of the second first-level revision. |
| 14 | +
|
| 15 | +You may assume the default revision number for each level of a version number to be 0. |
| 16 | +For example, version number 3.4 has a revision number of 3 and 4 for its first and second level revision number. |
| 17 | +Its third and fourth level revision number are both 0. |
| 18 | +
|
| 19 | +Note: |
| 20 | +
|
| 21 | +Version strings are composed of numeric strings separated by dots . and this numeric strings may have leading zeroes. |
| 22 | +Version strings do not start or end with dots, and they will not be two consecutive dots. |
| 23 | +*/ |
| 24 | +// time: 2019-01-07 |
| 25 | + |
| 26 | +package compareversionnumbers |
| 27 | + |
| 28 | +import ( |
| 29 | + "strconv" |
| 30 | + "strings" |
| 31 | +) |
| 32 | + |
| 33 | +// time complexity: O( max n, m ) |
| 34 | +// space complexity: O(n+m) |
| 35 | +func compareVersion(version1 string, version2 string) int { |
| 36 | + var ( |
| 37 | + v1 = strings.Split(version1, ".") |
| 38 | + v2 = strings.Split(version2, ".") |
| 39 | + ) |
| 40 | + for i := 0; i < len(v1) || i < len(v2); i++ { |
| 41 | + var v1N, v2N int |
| 42 | + if i < len(v1) { |
| 43 | + v1N, _ = strconv.Atoi(v1[i]) |
| 44 | + } |
| 45 | + if i < len(v2) { |
| 46 | + v2N, _ = strconv.Atoi(v2[i]) |
| 47 | + } |
| 48 | + |
| 49 | + if v1N > v2N { |
| 50 | + return 1 |
| 51 | + } else if v1N < v2N { |
| 52 | + return -1 |
| 53 | + } |
| 54 | + } |
| 55 | + return 0 |
| 56 | +} |
0 commit comments