Leetcode 153) Final Minimum in Rotated Sorted Array

image

내 답안

class Solution {
    public int findMin(int[] nums) {
        if(nums.length==1){
            return nums[0];
        }
        if(nums.length==2){
            if(nums[0]>nums[1]){
                return nums[1];
            }else{
                return nums[0];
            }
        }

        int l = 0;
        int r = nums.length-1;
        while(l+1<r){
            int mid = l+(r-l)/2 ;
            if(nums[l]<nums[mid] && nums[mid]>nums[r]){
                l=mid;
            }else if(nums[l]>nums[mid] && nums[r]>nums[mid]){
                r=mid;
            }else{
                return nums[0];
            }            
        }

        return nums[r];

    }
}

다른 답안

class Solution {
    /*
    l<mid -> l = mid 
    r<mid -> l = mid+1
    */
    public int findMin(int[] nums) {
        int l=0, r = nums.length-1, mid;
        while(l<r)
        {
            if(nums[l] < nums[r])
                return nums[l];

            mid = l + (r-l)/2;

            if(nums[mid]>nums[mid+1])
                return nums[mid+1];
            if(nums[mid-1] > nums[mid])
                return nums[mid];

            if(nums[l] < nums[mid])
                l = mid+1;
            else
                r = mid;
        }
        return nums[l];

    }
}

© 2018. All rights reserved.

Powered by Hydejack v8.5.2