• LeetCode 33. Search in Rotated Sorted Array Java


    题目:

    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.

    题意:最开始想到的是暴力求解,直接遍历数组,时间复杂度为o(n)。可以只用一次二分查找得到结果,时间复杂度为o(logn),因为链表只有一个地方被翻转了,那么肯定可以知道链表若从中间分为两半,一边是肯定有序的;(1)若左边有序,如果target在左边范围,那么继续查找,否则在另一边查找;(2)若右边有序,如果target在右边范围,继续查找,否则在左边查找

    代码:

    public class Solution {
        public int search(int[] nums, int target) {
            int start = 0;
            int end = nums.length-1;
    
            while(start <= end){
                int mid = (start + end) / 2;
                if(nums[mid] == target)
                    return mid;
                if(nums[start] <= nums[mid]){            //如果链表左边是有序的
                    if(nums[start] <= target && target < nums[mid]){            //若target在链表左边
                        end = mid - 1;
                    }else{
                        start = mid + 1;
                    }
    
                } else{     //否则,如果链表右边是有序的
                    if(nums[end] >= target && target > nums[mid]){
                        start = mid + 1;
                    }else{
                        end = mid-1;
                    }
                }
            }
            return -1;
        }
    }
  • 相关阅读:
    MyBatis学习总结(5)——实现关联表查询
    MyBatis学习总结4--解决字段名与实体类属性名不相同的冲突
    MyBatis学习总结3-优化MyBatis配置文件
    各种数据库的数据类型
    Ubuntu下jdk配置
    null和""的区别
    单例模式
    知识体系(不断更新)
    Servlet错误一览
    如何锻炼敲代码的能力
  • 原文地址:https://www.cnblogs.com/271934Liao/p/6902053.html
Copyright © 2020-2023  润新知