[Calculate daily] Rotate ordered arrays

Posted by bouncer on Mon, 07 Oct 2019 10:44:44 +0200

Find a given integer in a rotating ordered array and return its subscript in the array?

//Conventional ordered array
int[] arr1 = {1,2,3,4,5}
//Rotating ordered array
int[] arr2 = {50,60,70,80,20,30,40} 

Ideas for solving problems:

  1. Suppose that the left-most subscript is marked by left, the right-most subscript is marked by right, and the middle integer subscript is marked by mid.
  2. Whether the integer value corresponding to the subscript mid is larger than the integer value corresponding to the subscript left is ordered if it is larger than the integer value corresponding to the subscript left, and if it is less than the integer value corresponding to the subscript left is ordered.
  3. On the basis of the previous step, if the left side is ordered, it is judged whether the target value target is actually left or right. If on the left side, right = mid-1, otherwise left = mid+1;
  4. If the right side is ordered, determine whether the target value target is on the left or right. If on the right, left = mid+1, otherwise right = mid -1

The code is as follows:

public class Solution_2 {

    private static int findTargetIndex(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int mid;
        while (left <= right) {
            mid = (right - left) / 2 + left;
            if (nums[mid] == target) {
                return mid;
            }

            if (nums[mid] >= nums[left]) {
                //The instructions are ordered on the left.
                if (target >= nums[left] && target < nums[mid]) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } else {
                //The instructions are ordered on the right.
                if (target > nums[mid] && target <= nums[right]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        return -1;
    }


    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 1, 2, 3, 4, 5, 6,7};
        int target = 2;
        int targetIndex = findTargetIndex(arr, target);
        System.out.println("targetIndex = " + targetIndex);
    }
}

Topics: Java less