2022年10月25日 星期二

[153] Find Minimum in Rotated Sorted Array

找rotate array 的min
實在是好想linear search 找一輪return喔哈哈哈哈哈~(被出題者毆飛)
邊界值許多陷阱而我還在try & error 啊是不是砍掉重練好呢QQ


int findMin(int* nums, int numsSize){
    if(numsSize==1)
        return nums[0];
    if(numsSize==2)
        return( nums[0]<nums[1]?nums[0]:nums[1]);
    
    int low=0;
    int high = numsSize-1;
    int pivot;
    while(low < high)
    {
        if (high-low==1)
        {
            pivot = (nums[high]>nums[low])?low:high;
            break;
        }
        pivot= low + (high-low)/2;
        if (nums[pivot] < nums[high])
        {
            high=pivot;
        }
        else
        {
            low=pivot;
        }            
    }
    return nums[pivot];
}

沒有留言:

張貼留言