To solve this problem, we need to write a function that finds the minimum value in a given vector of integers. The function should handle edge cases such as an empty vector appropriately.
Approach
- Check for Empty Vector: First, we need to ensure the input vector is not empty. If it is, we throw an exception since an empty vector has no minimum value.
- Initialize Minimum Value: Start with the first element of the vector as the initial minimum value.
- Iterate Through the Vector: Loop through each element in the vector. For each element, if it is smaller than the current minimum value, update the minimum value.
- Return the Minimum Value: After processing all elements, return the minimum value found.
Solution Code
#include <vector>
#include <stdexcept>
int findMin(const std::vector<int>& nums) {
if (nums.empty()) {
throw std::invalid_argument("Input vector cannot be empty.");
}
int min_val = nums[0];
for (int num : nums) {
if (num < min_val) {
min_val = num;
}
}
return min_val;
}
Explanation
- Empty Vector Handling: The function checks if the vector is empty and throws an
invalid_argumentexception. This is a robust way to handle invalid input. - Initialization: The initial minimum value is set to the first element of the vector, which is safe since we've already checked the vector is non-empty.
- Iteration: Using a range-based for loop, we traverse each element. For each element, we compare it with the current minimum and update the minimum if the element is smaller.
- Efficiency: The algorithm runs in O(n) time complexity, where n is the number of elements in the vector. This is optimal because we need to check each element at least once to find the minimum. The space complexity is O(1) since we only use a constant amount of additional space.
This approach ensures that we efficiently and correctly find the minimum value in the vector while handling edge cases appropriately.


作者声明:本文包含人工智能生成内容。