fork download
  1. class Solution {
  2. public int search(int[] nums, int target) {
  3. int left = 0, right = nums.length - 1;
  4.  
  5. while (left <= right) {
  6. int mid = (left + right) / 2;
  7.  
  8. if (nums[mid] == target) return mid;
  9.  
  10. if (nums[left] <= nums[mid]) {
  11. if (target >= nums[left] && target < nums[mid]) {
  12. right = mid - 1;
  13. } else {
  14. left = mid + 1;
  15. }
  16. } else {
  17. if (target > nums[mid] && target <= nums[right]) {
  18. left = mid + 1;
  19. } else {
  20. right = mid - 1;
  21. }
  22. }
  23. }
  24.  
  25. return -1;
  26. }
  27.  
  28. public static void main(String[] args) {
  29. Solution solution = new Solution();
  30. int[] nums = {4, 5, 6, 7, 0, 1, 2};
  31. int target = 0;
  32. int result = solution.search(nums, target);
  33. System.out.println("Target found at index: " + result);
  34. }
  35. }
  36.  
Success #stdin #stdout 0.11s 53528KB
stdin
Standard input is empty
stdout
Target found at index: 4