Simple and easy understanding Java solution


  • 6
    M
    public int search(int[] nums, int target) {
    	        int pivot = findPivot(nums);
    	        return binarySearch(nums, 0, pivot, target) + binarySearch(nums, pivot + 1, nums.length - 1, target) + 1;
    	    }
    	 	
    	 	public int findPivot(int nums[]){
    	 		int i = 0, j = nums.length - 1;
    			while(i < j - 1){
    				int mid = i + (j - i) / 2;
    				if(nums[i] < nums[mid] && nums[j] < nums[mid]){
    					i = mid;
    				}else {
    					j = mid;
    				}
    			}
    	 		return i;
    	 	}
    	 	
    	 	public int binarySearch(int a[], int start, int end, int key){
    			int i = start, j = end;
    			while(i <= j){
    				int mid = i + (j - i) / 2;
    				if(a[mid] > key){
    					j = mid - 1;
    				}else if(a[mid] < key){
    					i = mid + 1;
    				}
    				else return mid;
    			}
    			return -1;
    		}

  • -4
    W
    public int findp(int[] nums) {
            for (int i = 1; i < nums.length; i++) {
                if (nums[i] < nums[i-1]) {
                    return i-1;
                }
            }
            return -1;
    }

  • 0
    S

    Your suggestion will require O(n) time complexity whereas solution in question is requiring just O(Logn) complexity.


Log in to reply
 

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