Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

search in rotated sorted array leetcode

class Solution {
    public int search(int[] nums, int target) {
        int pivot = FindPivot(nums);
        int a_pointer = 0;
        int b_pointer = nums.length-1;
        if (target >= nums[pivot] && target <= nums[b_pointer] ){
            a_pointer = pivot;
        }else{
            b_pointer = pivot;
        }
        if (nums[a_pointer] == target) return a_pointer;
        if (nums[b_pointer] == target) return b_pointer;
        while(a_pointer <= b_pointer){
            int midpoint = a_pointer + (b_pointer - a_pointer) / 2;
            if (nums[midpoint] == target) return midpoint;
            if (nums[midpoint] < target) a_pointer = midpoint + 1;
            if (nums[midpoint] > target) b_pointer = midpoint - 1;
        }
        return -1;
    }
    
    public static int FindPivot(int[] nums){

        int start = 0;
        int end = nums.length-1;

        while (start < end){
            int mid = start + (end-start)/2;
            if (nums[mid] > nums[end]){
                start = mid+1;
            }else end = mid;
        }
        return start;
    }
}
Comment

PREVIOUS NEXT
Code Example
Java :: next line java does not take input 
Java :: creating an object in java 
Java :: room insert and return id 
Java :: how to use Add Grepper Answer (a) 
Java :: add random numbers to array 
Java :: string length java 
Java :: unresolved reference activity_main 
Java :: different constructiors in java and what they do explained 
Java :: implement queue using array in java 
Java :: java sort reverse lambda 
Java :: array to array list java 
Java :: splash full screen android 
Java :: void * to int 
Java :: try catch block 
Java :: radix sort 
Java :: java spring mvc 
Java :: set array length java 
Java :: fabricmc concat text 
Java :: android java how to stop users fromgoing back too much 
Java :: how to choose an element in a array list Java 
Java :: natural log in java 
Java :: session management in java spring boot for login logut 
Java :: how to repeat string in java 
Java :: java.lang.NullPointerException: Cannot store to double array because is null 
Java :: java stream list order lambda 
Java :: Get generic type of class at runtime 
Java :: ejercicios de clases abstractas e interfaces en java 
Java :: Java Boolean Literals 
Java :: computeifabsent hashmap java 
Java :: android studio setbackgroundcolor drawable 
ADD CONTENT
Topic
Content
Source link
Name
9+4 =