zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    SpringMVC 通过post接收form参数或者json参数
    Web验证码图片的生成-基于Java的实现
    springmvc防止表单重复提交demo
    MyBatis多表映射demo
    mybatis配置ehcache缓存
    Oracle数据库Where条件执行顺序
    省选模拟10
    省选模拟8
    省选模拟9
    省选模拟7
  • 原文地址:https://www.cnblogs.com/chruny/p/4918379.html
Copyright © 2011-2022 走看看