81. Search in Rotated Sorted Array II
Posted panini
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了81. Search in Rotated Sorted Array II相关的知识,希望对你有一定的参考价值。
题目:
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?Would this affect the run-time complexity? How and why?
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
Write a function to determine if a given target is in the array.
The array may contain duplicates.
链接:https://leetcode.com/problems/search-in-rotated-sorted-array-ii/#/description
5/2/2017
顺序查找,O(N)
1 public class Solution { 2 public boolean search(int[] nums, int target) { 3 if (nums == null || nums.length == 0) { 4 return false; 5 } 6 for (int i = 0; i < nums.length; i++) { 7 if (nums[i] == target) { 8 return true; 9 } 10 } 11 return false; 12 } 13 }
别人的答案:worst case O(N)
https://discuss.leetcode.com/topic/8087/c-concise-log-n-solution
1 class Solution { 2 public: 3 bool search(int A[], int n, int target) { 4 int lo =0, hi = n-1; 5 int mid = 0; 6 while(lo<hi){ 7 mid=(lo+hi)/2; 8 if(A[mid]==target) return true; 9 if(A[mid]>A[hi]){ 10 if(A[mid]>target && A[lo] <= target) hi = mid; 11 else lo = mid + 1; 12 }else if(A[mid] < A[hi]){ 13 if(A[mid]<target && A[hi] >= target) lo = mid + 1; 14 else hi = mid; 15 }else{ 16 hi--; 17 } 18 19 } 20 return A[lo] == target ? true : false; 21 } 22 };
更多讨论
https://discuss.leetcode.com/category/89/search-in-rotated-sorted-array-ii
以上是关于81. Search in Rotated Sorted Array II的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 81. Search in Rotated Sorted Array II
81. Search in Rotated Sorted Array II
[Leetcode]81. Search in Rotated Sorted Array II
81. Search in Rotated Sorted Array II