【LeetCode】33. Search in Rotated Sorted Array - Java实现

文章目录

  • 1. 题目描述:
  • 2. 思路分析:
  • 3. Java代码:

1. 题目描述:

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

Your algorithm’s runtime complexity must be in the order of O(log n).

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

2. 思路分析:

题目的意思是在旋转有序数组中搜索一个给定值,若存在返回坐标,若不存在返回-1,要求时间复杂度为O(log N)。

此题可借鉴二分查找的思路去求解,难点在于该有序数组不知具体在哪个位置旋转了,例如给定数组:[0, 1, 2, 4, 5, 6, 7],有如下几种方式旋转:

0  1  2   4  5  6  7
7  0  1   2  4  5  6
6  7  0   1  2  4  5
5  6  7   0  1  2  4
4  5  6  7  0  1  2
2  4  5  6  7  0  1
1  2  4  5  6  7  0

可发现一个规律,当中间的数小于最右边的数时,数组右半部分有序;当中间的数大于最左边的数时,数组左半部分有序。由此可用二分查找法,很简单,具体见如下代码实现。

3. Java代码:

源代码:见我GiHub主页

代码:

public int search(int[] nums, int target) {
    int left = 0;
    int right = nums.length - 1;

    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) {
            return mid;
        }

        // 右边有序
        if (nums[mid] < nums[right]) {
            if (nums[mid] < target && nums[right] >= target) { // target 定在右半部分
                left = mid + 1;
            } else { // target 定在左半部分
                right = mid - 1;
            }
        } else { // 左边有序
            if (nums[mid] > target && nums[left] <= target) { // target 定在左半部分
                right = mid - 1;
            } else { // target 定在右半部分
                left = mid + 1;
            }
        }
    }
    return -1;
}

你可能感兴趣的:(【LeetCode】,【Java】,LeetCode题解,-,Java实现)