关闭

Search in Rotated Sorted Array II

170人阅读 评论(0) 收藏 举报
分类:

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.

public class Solution {
    /*it is a good question following the rotated sorted array 1*/
    /*eg 3  1 2 3 3 3, we don;t know where to go,left or right. so we just start ++ until they are different.*/
    //if all the elmement is same, and the target is not in the array.the time complexity is O(n)
    public boolean search(int[] nums, int target) {
        if(nums == null || nums.length == 0)
            return false;
        int low = 0;
        int high = nums.length - 1;
        while(low <= high) {
            int mid = (low + high) / 2;
            if(nums[mid] == target)
                return true;
            if(nums[mid] > nums[low]) {
                if(target >= nums[low] && target < nums[mid])
                    high = mid -1;
                else
                    low = mid + 1;
            }
            else if(nums[mid] < nums[low]) {
                if(target > nums[mid] && target <= nums[high])
                    low = mid + 1;
                else
                    high = mid -1;
            }
            //here is most important to solve the duplicate
            else  {
                low ++;
            }
        }

        return false;
    }
}
0
0

猜你在找
【直播】机器学习&数据挖掘7周实训--韦玮
【套餐】系统集成项目管理工程师顺利通关--徐朋
【直播】3小时掌握Docker最佳实战-徐西宁
【套餐】机器学习系列套餐(算法+实战)--唐宇迪
【直播】计算机视觉原理及实战--屈教授
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之矩阵--黄博士
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之凸优化--马博士
【套餐】Javascript 设计模式实战--曾亮
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:65663次
    • 积分:1297
    • 等级:
    • 排名:千里之外
    • 原创:70篇
    • 转载:19篇
    • 译文:0篇
    • 评论:1条
    最新评论