• leetcode------Search in Rotated Sorted ArrayII


    题目 Search in Rotated Sorted ArrayII
    通过率: 31.4%
    难度: 中等

    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.

    本题意思是会出现重复元素

    如:456701234;

    但是我发现我再第一版本中的做法是不受本题影响的,具体参照我第一个版本的做法

    代码如下:

     1 public class Solution {
     2     public boolean search(int[] A, int target) {
     3        int start=0,end=A.length-1,mid=0;
     4         while(start<=end){
     5             mid=(start+end)/2;
     6             if(A[mid]==target)return true;
     7             if(A[start]<A[mid]){
     8                 if((target<A[mid])&&(target>=A[start]))
     9                     end=mid-1;
    10                     else start=mid+1;
    11             }
    12             else if(A[start]>A[mid]){
    13                 if((target<A[mid])||(target>=A[start]))
    14                     end=mid-1;
    15                     else start=mid+1;
    16             }
    17             else start++;
    18         }
    19         return false;
    20     }
    21 }

    python:

     1 class Solution:
     2     # @param A, a list of integers
     3     # @param target, an integer to be searched
     4     # @return an integer
     5 
     6     def search(self, A, target):
     7         left = 0
     8         right = len(A) - 1
     9         while(left <= right):
    10             mid = (left + right) / 2
    11             if (A[mid] == target):
    12                 return True
    13             if (A[left] < A[mid]):
    14                 if (target >= A[left] and target < A[mid]):
    15                     right = mid - 1
    16                 else:
    17                     left = mid + 1
    18             elif (A[left] > A[mid]):
    19                 if (target > A[mid] and target <= A[right]):
    20                     left = mid + 1
    21                 else:
    22                     right = mid - 1
    23             else:
    24                 left += 1
    25         return False
  • 相关阅读:
    ccc pool
    ccc 模拟重力 正太分布
    ccc 正态分布
    ccc this 指针
    基本语法HelloWorld
    css选择器
    css基本语法
    表单
    表格
    超链接
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4287613.html
Copyright © 2020-2023  润新知