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

    class Solution {
    public:
        int search(int A[], int n, int target) {
            if (n < 1) return -1;
            
            int left = -1, right = n, mid;
            int last = A[n-1];
            while (left + 1 < right) {
                mid = (right + left) / 2;
                if (A[mid] < last) {
                    right = mid;
                } else if (A[mid] > last) {
                    left = mid;
                } else {
                    right = mid; // only when n == 1
                }
            }
            
            if (last > target) {
                right = n;
            } else if (last < target){
                left = -1;
            } else {
                return n-1;
            }
            while(left + 1 < right) {
                mid = (right + left) / 2;
                if (A[mid] < target) {
                    left = mid;
                } else if (A[mid] > target) {
                    right = mid;
                } else {
                    return mid;
                }
            }
            return -1; 
        }
    };

    先用二分找出分界元素,然后根据所要搜索数值和最后一个数的大小关系确定在那一段内搜索。

    第二轮:

    对于重复数字数组可以采用稍微简单一点的方法,不用先特地求出分界:

    class Solution {
    public:
        int search(vector<int>& nums, int target) {
            int len = nums.size();
            int lo = 0;
            int hi = len - 1;
            while (lo < hi) {
                int mid = (lo + hi) / 2;
                if (nums[mid] == target) {
                    return mid;
                }
                if (nums[mid] >= nums[lo]) {
                    if (nums[lo] <= target && nums[mid] >= target) {
                        hi = mid;
                    } else {
                        lo = mid + 1;
                    }
                } else {
                    if (nums[mid] <= target && nums[hi] >= target) {
                        lo = mid + 1;
                    } else {
                        hi = mid;
                    }
                }
            }
            if (lo < len && nums[lo] == target) {
                return lo;
            }
            return -1;
        }
    };

    当有重复数字是`nums[mid] >= nums[lo]`判断就会有问题了

  • 相关阅读:
    sed与正则用法收集
    第一学期网络技术知识总汇
    常用的windows注册表大全
    1-1 Linux系统安装
    用javascript写计算器
    closure
    Linux-Rhel6 恢复误删文件
    flask第十一篇——自定义url转换器
    flask第十篇——url_for【3】
    flask第九篇——url_for【2】
  • 原文地址:https://www.cnblogs.com/lailailai/p/3684170.html
Copyright © 2011-2022 走看看