Daily Coding Problem: Problem #1000

/**
 *This problem was asked by Uber.
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
Find the minimum element in O(log N) time.
You may assume the array does not contain duplicates.
For example, given [5, 7, 10, 3, 4], return 3.
 * */
class Problem_1000 {
    /*
    * Solution: Divide and Conquer, check left side and right side
    * Time:O(logn), Space:O(logn)
    * */
    fun findMin(array: IntArray): Int {
        return help(array, 0, array.lastIndex)
    }

    private fun help(array: IntArray, i: Int, j: Int): Int {
        //because array is sorted in ascending
        if (array[i] <= array[j]) {
            //so this one is the minimum of two side
            return array[i]
        }
        //compare left side and right side
        val mid = i + (j - i) / 2
        val leftSideMinimum = help(array, i, mid)
        val rightSideMinimum = help(array, mid + 1, j)
        return Math.min(leftSideMinimum, rightSideMinimum)
    }
}

 

posted @ 2021-09-18 11:28  johnny_zhao  阅读(21)  评论(0编辑  收藏  举报