Leetcode 165. Compare Version Numbers
You are given two version numbers, version1
and version2
, composed of one or more integers separated by a dot (.
). Each version number consists of multiple sections separated by dots. Each section within the version numbers contains only digits.
For example, version1 = "1.0"
and version2 = "1.0.0"
are valid version numbers.
You need to compare these version numbers to find out which one is greater, or if they are equal. The possible outcomes are:
1
if version1
> version2
-1
if version1
< version2
0
if version1
== version2
Note that:
1.0
is considered equal to 1.0.0
(trailing zeros can be ignored).1.0.0
is the same as 1.0
.version1
and version2
are always valid version strings.version1 = "1.01"
, version2 = "1.001"
.version1
and version2
by the dot .
to get a list of integers indicating each section of the version numbers.Here is the C++ implementation for comparing version numbers:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
std::vector<int> splitVersion(const std::string& version) {
std::vector<int> components;
std::stringstream ss(version);
std::string item;
while (std::getline(ss, item, '.')) {
components.push_back(std::stoi(item));
}
return components;
}
int compareVersion(std::string version1, std::string version2) {
std::vector<int> v1 = splitVersion(version1);
std::vector<int> v2 = splitVersion(version2);
int length = std::max(v1.size(), v2.size());
for (int i = 0; i < length; ++i) {
int num1 = (i < v1.size()) ? v1[i] : 0;
int num2 = (i < v2.size()) ? v2[i] : 0;
if (num1 > num2) {
return 1;
}
if (num1 < num2) {
return -1;
}
}
return 0;
}
// Example usage
int main() {
std::string version1 = "1.01";
std::string version2 = "1.001";
std::cout << compareVersion(version1, version2) << std::endl;
return 0;
}
.
takes O(n) where n is the length of the longest string version.Overall, the time complexity of the function is O(n + m).
Feel free to ask for any further clarifications or optimizations!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?