[Leetcode]Search in Rotated Sorted Array II
2016-01-23 13:19
381 查看
题目
Follow up for “Search in Rotated Sorted Array”:What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
题目要求
此题是Search in Rotated Sorted Array题目的扩展,要求判断经过翻转过的有序数组中是否含有target这个值。两个题目的差别在于有序数组中是否有重复的数字。两道题都是采用二分法,只是两道题的在条件判断时会有一些变种。解题思路
数组中没有重复数字。[left middle]和[middle right]至少有一个是有序的,我们就判断target是否在有序的那一半,如果在,则选择有序的那一半,否则选择无序的那一半。
数组中有重复数字
这种情况的难点在于,[left middle]和[middle right]无法直接通过比较两端指针指向判断是否有序。比如[1 3 1 1 1]这个数组只是根据left middle 和right并不能分辨出哪段数据是无序的。所以进行一个额外的操作,如果left,middle 和right指针指向的值都相等时,让left和right都向middle移动一次,这样最后就可以像1一样进行相同的判断了
代码
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: bool """ left, right = 0, len(nums) - 1 while left <= right: middle = (left + right) / 2 if nums[middle] == target: return True if nums[left] == nums[middle] == nums[right]: left += 1 right -= 1 continue if nums[left] <= nums[middle]: if target >= nums[left] and target < nums[middle]: right = middle - 1 else: left = middle + 1 elif nums[middle] <= nums[right]: if target > nums[middle] and target <= nums[right]: left = middle + 1 else: right = middle - 1 return False
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解