• [LeetCode]题解(python):033-Search in Rotated Sorted Array


    题目来源:

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


    题意分析:

      在一个翻转数组实现一个查找。(什么叫翻转数组,也就是,原来排好序的数组,选择一个点,将这个点之前的数放到数组的后面,不如4,5,6,7,1,2,3就是一个翻转数组)。


    题目思路:

      这道题目的思路和二分查找的思路相似,难度主要是在确定二分的位置。


    代码(python):

      

     1 class Solution(object):
     2     def search(self, nums, target):
     3         """
     4         :type nums: List[int]
     5         :type target: int
     6         :rtype: int
     7         """
     8         size = len(nums)
     9         first = 0;last = size
    10         while first != last:
    11             mid = (first + last) // 2
    12             if nums[mid] == target:
    13                 return mid
    14             if nums[first] <= nums[mid]:
    15                 if nums[first] <= target and target < nums[mid]:
    16                     last = mid
    17                 else:
    18                     first = mid + 1
    19             else:
    20                 if nums[mid] < target and target <= nums[last - 1]:
    21                     first = mid + 1
    22                 else:
    23                     last = mid
    24         return -1
    View Code

    转载请注明出处:http://www.cnblogs.com/chruny/p/4918379.html

  • 相关阅读:
    Sql例子Sp_ExecuteSql 带参数
    Flex显示麦克风当前音量
    无法将 flash.display::Sprite@156b7b1 转换为 mx.core.IUIComponent
    FMS (端口问题)如何穿透防火墙
    19:A*B问题
    6264:走出迷宫
    2753:走迷宫
    1792:迷宫
    换钱问题(经典枚举样例)
    1943(2.1)
  • 原文地址:https://www.cnblogs.com/chruny/p/4918379.html
Copyright © 2020-2023  润新知