// nums[low..high]范围上求最大值 low ... high N
int process(std::vector<int> &nums, int low, int high){
// nums[low..high]范围上只有一个数,直接返回,base case
if(low == high){
return nums[low];
}
// low ... high 不只一个数
int mid = low + (high - low) / 2;
int n1 = process(nums, low, mid);
int n2 = process(nums, mid + 1, high);
return std::max(n1, n2);
}
int getMax(std::vector<int> &nums){
if(nums.empty()){
throw std::runtime_error("param error");
}
return process(nums, 0, (int)nums.size() - 1);
}
算法:用递归方法求数组中的最大值
于 2018-07-06 14:57:00 首次发布