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;
        }
    

      

      

  • 相关阅读:
    跟光磊学Python开发-面向对象入门
    插件调用下推操作
    K3Wise老单获取单据行数
    git 添加和删除 global 的 remote.origin.url
    CSV转Excel格式
    java 下载文件
    windows下安装redis并设置自启动
    linxu jdk安装
    Linux安装部署Redis
    CentOS上安装MySQL(使用国内源)
  • 原文地址:https://www.cnblogs.com/apanda009/p/7262292.html
Copyright © 2011-2022 走看看