An beginner's C++ recursion solution

  • 0

    Definitely not the fastest and the most efficient solution, but get the job done.

    Basically, when I look at this question the first thought is to split the original vector into two child vectors. By doing that, I can end up to a vector that only contains one element. Then, I can work backward to the top level with the min value. But unfortunately it requires extra space as I create child vectors, which is O(n). Other than that, this method should work O(logn). Sorry if I do not compute this correctly, still learning these notations :)

    class Solution {
        int findMin(vector<int>& nums) {
            int size = nums.size();
            int mid = size / 2;
            if (size == 1) {
                return nums[0];
            vector<int> left(nums.begin(), nums.begin()+mid);
            vector<int> right(nums.begin()+mid, nums.end());
            int left_min = findMin(left);
            int right_min = findMin(right);
            return min(left_min, right_min);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.