zoukankan      html  css  js  c++  java
  • Search in Rotated Sorted Array leetcode的第33道题

    记一次leetcode刷题的理解

    题目描述:

    leeicode第33道题:

    假设按照升序排序的数组在预先未知的某个点上进行了旋转。

    ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。

    搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。

    你可以假设数组中不存在重复的元素。

    你的算法时间复杂度必须是 O(log n) 级别。

    示例 1:

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

    示例 2:

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

    这个题如果没有要求时间的复杂度为O(log n) 的话,非常的简单。既然要求了,说明这是这个题的关键也是难点。

    题目分析:

    看到logn这个时间算法复杂度,首先就会想到二分查找法,但是这个题目的特殊就在于是由两段有序数组组成。所以三个量的判断非常的关键,就是数组的首元素nums[0],中间值nums[mid],还有他的target,这三者的大小顺序的情况理清楚了,这个题就可以解出来了。三者有下面的三种情况,及其判定条件:

    实现代码如下:

     /**
         * @param nums
         * @param target
         * @return
         */
        public int searchInRotatedSortedArray(int[] nums,int target){
            int low = 0;
            int high = nums.length-1;
            while(low <= high){
                int mid = low +((high-low) >> 2);
                if(nums[mid]== target) return mid;
                else if((nums[mid]> target && target>=nums[0]) || (target >= nums[0] && nums[0] > nums[mid]) || (target < nums[mid] && nums[mid]< nums[0]))
                    high = mid -1;
                else low = mid+1;
            }
            return -1;
        }
    
    

    测试:

    public static void main(String[] args) {
            int[] nums = {4,5,6,7,0,1,2};
            int index = new SearchInRotatedSortedArray().searchInRotatedSortedArray(nums,0);
            System.out.println(index);
        }
    

    输出结果:

    4
    

    但是上面得判断条件比较繁琐,我们可以使用Java中得异或来解决。改进如下(改进如下(参考leetcode某大神的解法))

    public int searchInRotatedSortedArray(int[] nums,int target){
            int low = 0;
            int high = nums.length-1;
            while(low < high){
                int mid = low +((high-low) >> 2);
               if((nums[0] > target) ^ (nums[0] > nums[mid]) ^ (target > nums[mid]))
                   low = mid+1;
               else high = mid;
            }
            return low == high && nums[low] == target ? low : -1;
        }
    

    测试:

    public static void main(String[] args) {
            int[] nums = {4,5,6,7,0,1,2};
            int index = new SearchInRotatedSortedArray().searchInRotatedSortedArray(nums,0);
            System.out.println(index);
        }
    

    输出结果:

    4
    

    这个题的关键使用二分法来确定查找的区间非常的重要。

  • 相关阅读:
    空值判断(is not null)
    http协议相关面试题
    Linux基本面试题。(感觉也就这几个了)
    1、了解django运行流程
    python笔试常见题
    selenium中一些可能用到的js操作
    元素判断
    二次封装
    关于在阿里云上面安装mysql遇到的一些问题。
    linux常用的一些基本命令
  • 原文地址:https://www.cnblogs.com/chentang/p/13194964.html
Copyright © 2011-2022 走看看