Find Minimum in Rotated Sorted Array - LeetCode

eclaircpeclaircp
1 min read

Problem Link

C++ Code

class Solution {
public:
    int findMin(vector<int>& nums) {

        int low = 0;
        int high = nums.size() - 1;

        int ans = INT_MAX;

        while(low <= high) {

            int mid = low + (high-low)/2;

            if(nums[low] <= nums[mid]) {

                ans = min(ans, nums[low]);
                low = ++mid;

            } else {

                ans = min(ans, nums[mid]);
                high = --mid;

            }

        }

        return ans;
    }
};

TypeScript Code

function findMin(nums: number[]): number {

    let low: number = 0;
    let high: number = nums.length - 1;

    let ans: number = Number.MAX_VALUE;

    while(low <= high) {

        let mid = low + Math.floor((high-low)/2);

        if(nums[low] <= nums[mid]) {

            ans = Math.min(ans, nums[low]);
            low = ++mid;

        } else {

            ans = Math.min(ans, nums[mid]);
            high = --mid;

        }

    }

    return ans;
};

Go Code

func findMin(nums []int) int {

    low := 0;
    high := len(nums) - 1;

    ans := math.MaxInt32;

    for low <= high {

        mid := low + (high-low)/2;

        if(nums[low] <= nums[mid]) {

            if nums[low] < ans {
                ans = nums[low];
            }

            low = mid+1;

        } else {

            if nums[mid] < ans {
                ans = nums[mid];
            }

            high = mid-1;

        }

    }

    return ans;
}
0
Subscribe to my newsletter

Read articles from eclaircp directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

eclaircp
eclaircp