Here is my solution - which can answer both question Find Minimum in Rotated Sorted Array and II


  • 1
    R

    public class Solution {

    public int findMin(int[] num) {
    	int start = 0;
    	int end = num.length - 1;
    	int mid = (start + end) / 2;
    	int result = 0;
    	if (start == end || isSort(splitArray(num, start, end))) {
    		result = num[0];
    	} else if (isSort(splitArray(num, start, mid - 1))
    			&& isSort(splitArray(num, mid + 1, end))) {
    		if (num[mid] <= splitArray(num, mid + 1, end)[0]
    				&& num[mid] <= splitArray(num, start, mid - 1)[0]) {
    			result = num[mid];
    		} else {
    			result = num[mid + 1];
    		}
    	} else if (isSort(splitArray(num, start, mid - 1))
    			&& !isSort(splitArray(num, mid + 1, end))) {
    		result = findMin(splitArray(num, mid + 1, end));
    	} else if (!isSort(splitArray(num, start, mid - 1))
    			&& isSort(splitArray(num, mid + 1, end))) {
    		result = findMin(splitArray(num, start, mid - 1));
    	}
    	return result;
    
    }
    
    public boolean isSort(int[] num) {
    	boolean flag = true;
    	for (int i = 0; i < num.length - 1; i++) {
    		if (num[i] > num[i + 1]) {
    			flag = false;
    		}
    	}
    	return flag;
    
    }
    
    public int[] splitArray(int[] num, int start, int end) {
    	int[] numArray = new int[end - start + 1];
    	if (start == end) {
    		numArray[0] = num[start];
    	} else {
    		for (int i = start; i <= end; i++) {
    			numArray[i - start] = num[i];
    		}
    	}
    	return numArray;
    }
    

    }


Log in to reply
 

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