33.leetcode题目讲解(Python):搜索旋转排序数组
2018-11-16 本文已影响47人
夏山闻汐
题目如下:
题目
这道题比较简单,不做过多解释了,注意程序终止条件,参考代码如下:
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if len(nums) == 0:
return -1
if len(nums) == 1:
if target == nums[0]:
return 0
else:
return -1
if target < nums[0]:
j = -1
while j >= - len(nums):
if target == nums[j]:
return len(nums) + j
if target < nums[j]:
if j - 1 >= - len(nums):
if nums[j-1] <= nums[j]:
j = j - 1
continue
else:
return -1
else:
return -1
if target > nums[j]:
return -1
if target == nums[0]:
return 0
if target > nums[0]:
i = 0
while i < len(nums):
if target == nums[i]:
return i
if target > nums[i]:
if i + 1 < len(nums):
if nums[i] <= nums[i+1]:
i = i + 1
continue
else:
return -1
else:
return -1
if target < nums[i]:
return -1
源码地址:
https://github.com/jediL/LeetCodeByPython
其它题目:[leetcode题目答案讲解汇总(Python版 持续更新)]
(https://www.jianshu.com/p/60b5241ca28e)
ps:如果您有好的建议,欢迎交流 :-D,
也欢迎访问我的个人博客 苔原带 (www.tundrazone.com)