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

  • 相关阅读:
    第3章 MFC框架程序剖析
    第2章 掌握C++
    第1章 Windows程序内部运行机制
    【MFC】画线
    使用RegSetValueEx修改注册表时遇到的问题(转)
    读书笔记
    POJ 1182[并查集]
    读书笔记
    HihoCoder 1532 : 最美和弦
    HihoCode 1531 : 德国心脏病
  • 原文地址:https://www.cnblogs.com/chruny/p/4918379.html
Copyright © 2011-2022 走看看