leetCode练习(81)

来源:互联网 发布:mastercam9.1四轴编程 编辑:程序博客网 时间:2024/06/08 09:36

题目:Search in Rotated Sorted Array II

难度:medium

问题描述:

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.

Subscribe to see which companies asked this question

解题思路:

在原题的基础上使得可以字符重复。将原来的target与nums[mid]的比较从原来的两种情况(大于或小于等于)分为三种,大于,小于和等于,一次进行判断即可。

代码如下:

public class Solution {    public boolean search(int[] nums, int target) {        int head=0,tail=nums.length;        while(head<tail){        int mid=(head+tail)/2;        if(nums[mid]==target){        return true;        }        if(nums[mid]>nums[head]){        if(target<nums[mid]&&target>=nums[head]){        tail=mid;        }else{        head=mid+1;        }        }else if(nums[mid]<nums[head]){        if(target>nums[mid]&&target<nums[head]){        head=mid+1;        }else{        tail=mid;        }        }else{        head++;        }        }        return false;    }}

0 0
原创粉丝点击