import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 如果目标值存在返回下标,否则返回 -1
     * @param nums int整型一维数组 
     * @param target int整型 
     * @return int整型
     */
    public int search (int[] nums, int target) {

        if (nums == null || nums.length == 0) {
            return -1;
        }
        //附带找右边界
        int rightIndex = binarySearchForRightIndex(nums, 0, nums.length - 1, target);
        return binarySearchForLeftIndex(nums, 0, nums.length - 1, target);
    }

    public int binarySearchForLeftIndex (int[] nums, int left, int right, int target) {

        while (left <= right) {

            int mid = left + (right - left) / 2;

            if (nums[mid] == target) {
                right = mid - 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }

        if (nums[left] == target) {
            return left;
        }

        return -1;
    }

    public int binarySearchForRightIndex (int[] nums, int left, int right, int target) {

        while (left <= right) {

            int mid = left + (right - left) / 2;

            if (nums[mid] == target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }

        //[-2],-3 第一次right就往左移了right=-1 越界了
        if (right >= 0 &&nums[right] == target) {
            return right;
        }

        return -1;
    }
}