Java solution of using recursion


  • 0
    T
    public class Solution {
    public boolean search(int[] nums, int target) {
        return internalSearch(nums, target, 0, nums.length -1);   
    }
    public boolean internalSearch(int[] nums, int target, int lo, int hi) {
        if(lo > hi) return false;
        if(lo == hi) return nums[lo] == target;
        
        int mid = (lo+hi)/2;
        if(nums[mid] == target) return true;
        if(nums[mid] > nums[lo]) {
            if(target< nums[mid] && target>=nums[lo]) return internalSearch(nums, target, lo, mid-1);
            else return internalSearch(nums,target, mid+1, hi);
        } else if(nums[mid] < nums[lo]) {
            if(target > nums[mid] && target < nums[lo]) return internalSearch(nums, target, mid+1, hi);
            else return internalSearch(nums, target, lo, mid-1);
        } else return internalSearch(nums, target, lo, mid-1) || internalSearch(nums, target, mid+1, hi);
    }
    }

Log in to reply
 

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