码迷,mamicode.com
首页 > 其他好文 > 详细

81. Search in Rotated Sorted Array II

时间:2017-05-03 14:36:34      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:follow   tco   cas   lex   ase   time   unknown   i++   asc   

题目:

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

标签:follow   tco   cas   lex   ase   time   unknown   i++   asc   

原文地址:http://www.cnblogs.com/panini/p/6801636.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!