gpt4 book ai didi

Search in Rotated Sorted Array(在旋转排序数组中进行搜索)

转载 作者:bug小助手 更新时间:2023-10-24 18:36:11 27 4
gpt4 key购买 nike



Problem statement:

问题陈述:



There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is possibly rotated at an unknown pivot index 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.



I have written the exact similar code given in submissions for the problem, but, it fails for one of my output. I am unable to find the reason. Am I missing some logic?

我已经为这个问题编写了与提交中给出的完全类似的代码,但是,对于我的一个输出,它失败了。我找不到原因。我是不是错过了什么逻辑?


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;
}
}

The code fails to provide output for
nums = [6,7,1,2,3,4,5] and target = 7.

代码无法提供数字=[6,7,1,2,3,4,5]和目标=7的输出。


Expected output is 1, actual output is -1.

预期输出为1,实际输出为-1。


更多回答
优秀答案推荐

Disgusting mistake, we usually don't look at simple initialization twice ;) and I've been going through main algo body first. But debugging would help.

令人讨厌的错误,我们通常不会看两次简单的初始化;)而我一直在先看主要的算法主体。但调试会有所帮助。


Replace

替换


int left = nums[0];

with

使用


int left = 0;

更多回答

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com