One more accepted Java code with recursion


  • 1
    P
    public int findMin(int[] num) {
        return min(num, 0, num.length-1);
    }
    
    int min(int[] num, int left, int right) {
    	if (right - left <= 1) {
    		return num[left] < num[right] ? num[left] : num[right];
    	}
    	int mid = (right+left)/2;
    	if (num[mid] < num[right]) {
    		return min(num, left, mid);
    	} else if (num[mid] > num[right]) {
    		return min(num, mid, right);
    	} else {
    		int leftMin = min(num, left, mid);
    		int rightMin = min(num, mid, right);
    		return leftMin < rightMin ? leftMin : rightMin;
    	}
    }

  • 0
    C

    Why did you use

    if (right - left <= 1) {
        return num[left] < num[right] ? num[left] : num[right];
    }
    

    as the base case?

    I came up with almost the exact same algorithm, but used:

    if (left >= right) {
        return num[left];
    }

  • 0
    P

    If indices are the same or follow one by one but right is greater.
    In you case when indexes are the same or right and left are swaped.


Log in to reply
 

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