【二分查找】Leetcode 33. 搜索旋转排序数组【中等】

搜索旋转排序数组

整数数组 nums 按升序排列,数组中的值 互不相同

  • 在传递给函数之前,nums 在预先未知的某个下标 k(0 <= k < nums.length)上进行了 旋转,使数组变为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下标 从 0 开始 计数)。例如, [0,1,2,4,5,6,7] 在下标 3 处经旋转后可能变为 [4,5,6,7,0,1,2] 。

给你 旋转后 的数组 nums 和一个整数 target ,如果 nums 中存在这个目标值 target ,则返回它的下标,否则返回 -1 。

你必须设计一个时间复杂度为 O(log n) 的算法解决此问题。

示例 1:

输入 :nums = [4,5,6,7,0,1,2], target = 0
输出: 4

解题思路

  • 1、使用二分查找算法,在旋转后的有序数组中查找目标值。
  • 2、根据二分查找的思想,不断缩小搜索范围,直到找到目标值或者搜索范围为空。
  • 3、首先判断当前搜索范围内的数组部分是否是有序的:
复制代码
   如果是有序的,则直接在有序部分进行二分查找;
复制代码
   如果不是有序的,则根据中间点位置,调整搜索范围。
  • 4、不断循环以上步骤,直到找到目标值或者搜索范围为空。

思路:旋转数组一定是一边有序的,通过有序部分判断查找范围,不断缩小查找范围,直到找到元素

java实现

java 复制代码
public class SearchRotatedSortedArray {
    public int search(int[] nums, int target) {
        //left 为数组的起始索引
        int left = 0;
        //右指针 right 为数组的结束索引
        int right = nums.length - 1;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] >= nums[left]) { // 左半部分有序
                if (target >= nums[left] && target < nums[mid]) {
                    //数据就在左半部分,赋值right = mid-1
                    right = mid - 1;
                } else {
                    //数值不在左半部分,赋值left= mid+1
                    left = mid + 1;
                }
            } else { // 右半部分有序(同上)
                if (target > nums[mid] && target <= nums[right]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        
        return -1;
    }

    public static void main(String[] args) {
        SearchRotatedSortedArray searchRotatedSortedArray = new SearchRotatedSortedArray();
        int[] nums = {4,5,6,7,0,1,2};
        int target = 0;
        int result = searchRotatedSortedArray.search(nums, target);
        System.out.println("Index of target: " + result); // Output: 4
    }
}

时间空间复杂度

  • 时间复杂度:O(log n),其中n为数组nums的长度。因为使用了二分查找算法。

  • 空间复杂度:O(1)。

相关推荐
杨间34 分钟前
《排序算法全解析:从基础到优化,一文吃透八大排序!》
c语言·数据结构·排序算法
Remember_99339 分钟前
【LeetCode精选算法】滑动窗口专题二
java·开发语言·数据结构·算法·leetcode
Gorgous—l1 小时前
数据结构算法学习:LeetCode热题100-动态规划篇(下)(单词拆分、最长递增子序列、乘积最大子数组、分割等和子集、最长有效括号)
数据结构·学习·算法
北京地铁1号线2 小时前
2.3 相似度算法详解:Cosine Similarity 与 Euclidean Distance
算法·余弦相似度
圣保罗的大教堂2 小时前
leetcode 1895. 最大的幻方 中等
leetcode
Remember_9932 小时前
【LeetCode精选算法】滑动窗口专题一
java·数据结构·算法·leetcode·哈希算法
小饼干超人3 小时前
详解向量数据库中的PQ算法(Product Quantization)
人工智能·算法·机器学习
你撅嘴真丑3 小时前
第四章 函数与递归
算法·uva
漫随流水3 小时前
leetcode回溯算法(77.组合)
数据结构·算法·leetcode·回溯算法
玄冥剑尊3 小时前
动态规划入门
算法·动态规划·代理模式