zoukankan      html  css  js  c++  java
  • Search in Rotated Sorted Array

    Suppose a sorted array 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).
    
    You are given a target value to search. If found in the array return its index, otherwise return -1.
    
    You may assume no duplicate exists in the array.
    
    Have you met this question in a real interview? Yes
    Example
    For [4, 5, 1, 2, 3] and target=1, return 2.
    
    For [4, 5, 1, 2, 3] and target=0, return -1.
    
    Challenge 
    O(logN) time
    
    Tags 
    Sorted Array Array LinkedIn Binary Search Uber Facebook
    Related Problems 
    Medium Search in Rotated Sorted Array II 40 %
    Easy Search a 2D Matrix

    有序数组的题, 二分法, 根据mid的位置再确定start 和end的位置, 画图分情况

      三种情况

    The idea is that when rotating the array, there must be one half of the array that is still in sorted order.
    For example, 6 7 1 2 3 4 5, the order is disrupted from the point between 7 and 1. So when doing binary search, we can make a judgement that which part is ordered and whether the target is in that range, if yes, continue the search in that half, if not continue in the other half.

    public int search(int[] nums, int target) {
            if (nums == null || nums.length == 0) {
                return -1;
            }
            int beg = 0, end = nums.length - 1;
            while (beg + 1 < end) {
                int mid = beg + (end - beg) / 2;
                if (nums[mid] == target) {
                    return mid;
                }
                if (nums[mid] > nums[end]) {
                    if (nums[mid] > target && nums[beg] <= target) {
                        end = mid;
                    } else {
                        beg = mid;
                    }
                } else if (nums[mid] < nums[beg]) {
                    if (nums[mid] < target && target <= nums[end]) {
                        beg = mid;
                    } else {
                        end = mid;
                    }
                } else {
                    if (nums[mid] > target) {
                        end = mid;
                    } else {
                        beg = mid;
                    }
                }
            }
            if (nums[beg] == target) {
                return beg;
            }
            if (nums[end] == target) {
                return end;
            }
            return -1;
        }
    

      

      

  • 相关阅读:
    简单背包问题
    拓扑排序
    SPFA--P3905 道路重建
    Floyd--P1119 灾后重建
    Kmp--P3375 【模板】KMP字符串匹配
    练习 后缀数组
    BZOJ1036: [ZJOI2008]树的统计Count(树链剖分)
    BZOJ1503: [NOI2004]郁闷的出纳员(Splay)
    BZOJ2733: [HNOI2012]永无乡(线段树合并)
    BZOJ4196: [Noi2015]软件包管理器(树链剖分)
  • 原文地址:https://www.cnblogs.com/apanda009/p/7262292.html
Copyright © 2011-2022 走看看