leetcode 33.搜索旋转排序数组

⭐️ 题目描述


🌟 leetcode链接:搜索旋转排序数组

ps: 本题是二分查找的变形,旋转排序数组之后其实会形成两个有序的区间 。算出平均下标先判断是否与 target 相等,因为这样可以减少代码的冗余。如果前者不成立则使用平均下标元素 midIndex 与 数组最后一个元素判断大小(因为我们可以确定第二个有序区间的最大值,而确定不了第一个有序区间的最大值),若小于则当前 midIndex 就在第二个有序区间中,反之在第一个有序区间。知道在哪个区间后,在判断 target 是否在这个区间中以及 nums[midIndex]target 的大小。

代码:

c 复制代码
int search(int* nums, int numsSize, int target){
    int left = 0;
    int right = numsSize - 1;
    while (left <= right) {
        int midIndex = left + ((right - left) / 2);
        if (nums[midIndex] == target) {
            return midIndex;
        } else if (nums[midIndex] < nums[right]) {
            // 在第二个有序区间
            if (target <= nums[right] && nums[midIndex] < target) {
                left = midIndex + 1;
            } else {
                right = midIndex - 1;
            }
        } else {
            // 第一个有序区间
            if (target >= nums[left] && nums[midIndex] > target) {
                right = midIndex - 1;
            } else {
                left = midIndex + 1;
            }
        }
    }
    return -1;
}

相关推荐
旖旎夜光1 小时前
Linux(4)(下)
linux·学习
敲敲了个代码4 小时前
从硬编码到 Schema 推断:前端表单开发的工程化转型
前端·javascript·vue.js·学习·面试·职场和发展·前端框架
TimberWill7 小时前
哈希-02-最长连续序列
算法·leetcode·排序算法
Morwit7 小时前
【力扣hot100】64. 最小路径和
c++·算法·leetcode
我命由我123457 小时前
SVG - SVG 引入(SVG 概述、SVG 基本使用、SVG 使用 CSS、SVG 使用 JavaScript、SVG 实例实操)
开发语言·前端·javascript·css·学习·ecmascript·学习方法
leoufung7 小时前
LeetCode 373. Find K Pairs with Smallest Sums:从暴力到堆优化的完整思路与踩坑
java·算法·leetcode
Fern_blog9 小时前
鸿蒙学习之路
学习
小智RE0-走在路上9 小时前
Python学习笔记(11) --数据可视化
笔记·python·学习
LYFlied11 小时前
【每日算法】LeetCode 64. 最小路径和(多维动态规划)
数据结构·算法·leetcode·动态规划
Asus.Blogs12 小时前
SSE + Resty + Goroutine + Channel 完整学习笔记
笔记·学习·golang