Leetcode.33搜索旋转排序数组
题目:原题链接
整数数组 nums 按升序排列,数组中的值 互不相同 。
在传递给函数之前,nums 在预先未知的某个下标 k(0 <= k < nums.length)上进行了 旋转,使数组变为 [nums[k], nums[k+1], …, nums[n-1], nums[0], nums[1], …, nums[k-1]](下标 从 0 开始 计数)。例如, [0,1,2,4,5,6,7] 在下标 3 处经旋转后可能变为 [4,5,6,7,0,1,2] 。
给你 旋转后 的数组 nums 和一个整数 target ,如果 nums 中存在这个目标值 target ,则返回它的索引,否则返回 -1 。
思路:
(先更新一种方法,要去搬砖了)
- 这个和153题不同的是,这个不是求最小值,而是你找到target值需要经过多少个数
- 仍然是暴力求解法
- 先判断是否在数组里面,否则返回-1
- 遍历数组,如果相等直接跳出循环啦
- 如果不相等,就记录已经搜索的个数啦
- 最后返回count就可以啦
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
count = 0;
if target not in nums:
return -1
else:
for num in nums:
if num==target:
break
else:
count+=1
return count
哈哈哈哈,一开始没看题以为找到就可以了,我说咋一直解答错误,要读题读题读题