在旋转排序数组中搜索

问题描述 投票:0回答:1

问题陈述: 有一个按升序排序的整数数组 nums (具有不同的值)。 在传递给您的函数之前,nums 可能会在未知的枢轴索引 k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.

我已经编写了与该问题提交中给出的完全相同的代码,但是,我的输出之一失败了。我找不到原因。我是否缺少一些逻辑?请建议。

class Solution {
    public int search(int[] nums, int target) {
        int left = nums[0];
        int right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (target == nums[mid]) {
                return mid;
            } else {
                // if left sorted
                if (nums[left] <= nums[mid]) {
                    if (nums[left] <= target && target < nums[mid]) {
                        right = mid - 1;
                    } else {
                        left = mid + 1;
                    }
                } else {
                    // else right sorted
                    if (nums[mid] < target && target <= nums[right]) {
                        left = mid + 1;
                    } else {
                        right = mid - 1;
                    }
                }
            }
        }
        return -1;
    }
}

代码无法提供以下输出: nums = [6,7,1,2,3,4,5] 且目标 = 7 ; 预期输出 = 1,实际输出 = -1

java algorithm binary-search-tree binary-search leetcode
1个回答
0
投票

令人厌恶的错误,我们通常不会过多关注简单的初始化;)

改变

int left = nums[0];

int left = 0;
© www.soinside.com 2019 - 2024. All rights reserved.