Day21 搜索旋转排序数组

实际含义:在旋转数组中查找某元素

升序排列的整数数组 nums 在预先未知的某个点上进行了旋转(例如, [0,1,2,4,5,6,7] 经旋转后可能变为 [4,5,6,7,0,1,2] )。请你在数组中搜索 target ,如果数组中存在这个目标值,则返回它的索引,否则返回 -1

https://leetcode-cn.com/problems/search-in-rotated-sorted-array/

示例1:

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

示例2:

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

示例3:

输入:nums = [1], target = 0
输出:-1

提示:

1 <= nums.length <= 5000
-10^4 <= nums[i] <= 10^4
nums 中的每个值都 独一无二
nums 肯定会在某个点上旋转
-10^4 <= target <= 10^4

Java解法

思路:

  • 说实话,没看懂意思,中等题,但看起来就是查找某元素,提交试试看看怎么理解有误:怕是逗我,竟然过了
  • 使用二分优化查找
package sj.shimmer.algorithm.ten_3;

/**
 * Created by SJ on 2021/2/14.
 */

class D21 {
    public static void main(String[] args) {
        System.out.println(search2(new int[]{4,5,6,7,8,1,2,3}, 8));
//        System.out.println(search(new int[]{4, 5, 6, 7, 0, 1, 2}, 4));
//        System.out.println(search2(new int[]{4, 5, 6, 7, 0, 1, 2}, 0));
//        System.out.println(search2(new int[]{4, 5, 6, 7, 0, 1, 2}, 3));
    }

    public static int search(int[] nums, int target) {
        int index = -1;
        for (int i = 0; i < nums.length; i++) {
            if (target == nums[i]) {
                index = i;
                break;
            }
        }
        return index;
    }

    public static int search2(int[] nums, int target) {
        int length = nums.length;
        if (length ==1&&nums[0]==target) {
            return 0;
        }
        int start = 0;
        int end = length -1;
        while (start<=end) {
            int mid = (end+start) / 2;
            if (nums[mid]==target) {
                return mid;
            }
            if (nums[0] <= nums[mid]) {
                if (nums[0] <= target && target < nums[mid]) {
                    //正常升序且包含
                    end = mid - 1;
                } else {
                    start = mid + 1;
                }
            } else {
                if (nums[mid] < target && target <= nums[length - 1]) {
                    //后半段正常升序且包含
                    start = mid + 1;
                } else {
                    end = mid - 1;
                }
            }
        }
        return -1;
    }
}
image

官方解

https://leetcode-cn.com/problems/search-in-rotated-sorted-array/solution/sou-suo-xuan-zhuan-pai-xu-shu-zu-by-leetcode-solut/

  1. 二分查找

    我太年轻了,这是考查二分查找的,我竟然没有想到,菜

    二分查找注意判断条件:在有序的半段中进行判断,从而确定下次对半查找的位置

    if (nums[0] <= nums[mid]) {
        if (nums[0] <= target && target < nums[mid]) {
            //正常升序且包含
            end = mid - 1;
        } else {
            start = mid + 1;
        }
    } else {
        if (nums[mid] < target && target <= nums[length - 1]) {
            //后半段正常升序且包含
            start = mid + 1;
        } else {
            end = mid - 1;
        }
    }
    
    • 时间复杂度: O(logn)

    • 空间复杂度: O(1)

你可能感兴趣的:(Day21 搜索旋转排序数组)