33/81. Search in Rotated Sorted Array I/II(C++)

本文介绍在旋转后的有序数组中搜索目标值的方法。针对无重复元素的情况,通过判断一半有序的特点进行二分查找;对于允许重复元素的情况,提出改进算法应对运行时间复杂度的挑战。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注

  1. Search in Rotated Sorted Array

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.

// 总有一边是有序的,用有序的那边作为判断,若不在有序的那边则在另一边
class Solution {
public:
    int search(vector<int>& nums, int target) {
        int first = 0, last = nums.size();
        while (first != last) { // 直到first和last相等则退出循环
            const int mid = first + (last - first) / 2;
            if (nums[mid] == target)
                return mid;
            if(nums[first] <= nums[mid]) {   // 若左半边有序
                if (nums[first] <= target && target < nums[mid])
                    last = mid; // 缩小范围到左半边
                else
                    first = mid + 1;// 否则在右半边
            } else {  // 若右边有序
                if (nums[mid] < target && target <= nums[last - 1])
                    first = mid + 1; // 缩小范围到右半边
                else
                    last = mid; // 否则在左半边
            }
        }
        return -1;
    }
};
  1. Search in Rotated Sorted Array II

Follow up for “Search in Rotated Sorted Array”:
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?
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).

Write a function to determine if a given target is in the array.

The array may contain duplicates.

// 如果A[m] >= A[l]不能确定递增,则拆成两个可能:
// (1)若A[m] > A[l],则区间[l,m]一定递增;
// (2)若A[m] == A[l],那就l++,往下继续看。
class Solution {
public:
    bool search(vector<int>& nums, int target) {
        int first = 0, last = nums.size();
        while (first != last) {
            const int mid = first + (last - first) / 2;
            if (nums[mid] == target)
                return true;
            if (nums[first] < nums[mid]) {
                if (nums[first] <= target && target < nums[mid])
                    last = mid;
                else 
                    first = mid + 1;
            } else if (nums[first] > nums[mid]) {
                if (nums[mid] < target && target <= nums[last-1])
                    first = mid + 1;
                else
                    last = mid;
            } else
                //skip duplicate one
                first++;
        }
        return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值