zoukankan      html  css  js  c++  java
  • [LeetCode] Search in Rotated Sorted Array

    题目要求:  

      Suppose a sorted array 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),这里就需要思考其他的解法。

      对于这个部分有序的数组可以试着采用二分查找,需要解决的问题是如何去缩小查找目标所在的范围。

      反转的有序数组可能出现以下三种情况:

      

      我们可以据此分情况讨论,具体参见代码

      

    int search(int* nums, int numsSize, int target) {
        int first = 0, end = numsSize - 1;
        
        while(first <= end){
            int mid = first + (end - first) / 2;
            if(nums[mid] == target)
                return mid;
            
            if(nums[first] <= nums[mid]){
                if(nums[first] <= target && nums[mid] > target)
                    end = mid - 1;
                else
                    first = mid + 1;
            }
            else{
                if(nums[mid] < target && nums[end] >= target)
                    first = mid + 1;
                else
                    end = mid - 1;
            }
        }
        return -1;
    }

      

  • 相关阅读:
    OCM_Session1_2_Server-side Network Configuration
    sql union代替or
    创建组合索引SQL从1个多小时到1S的案例
    OCM_session0手动建库实验
    慎用位图索引
    Java之List排序
    Java之List排序出错
    dojo、iframe和FusionCharts兼容性
    Java之indexOf()方法
    Java之split()方法
  • 原文地址:https://www.cnblogs.com/codinglol/p/4671984.html
Copyright © 2011-2022 走看看