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

    Title:

    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.

    思路:还是二分搜索,但是对于一个中间值,如何处理是左加还是右加呢?考虑下,旋转之后的数组,中间值会将原来的数组划分为左右两个数组,其中一个是有序的。所以我们需要做的事就是判断那边是有序的。如何判断有序呢?只要将中间值和最左边的值比较,如果大于,则左边是有序,如果小于,则右边有序,如果相等,则有重复元素只能一个个处理。

    class Solution {
    public:
        int search(int A[], int n, int target) {
            int l = 0;
            int h = n-1;
            while (l <= h){
                int m = (l+h)/2;
                if (A[m] == target)
                    return m;
                if (A[m] > A[l]){
                    if (target >= A[l] && target < A[m])
                        h = m-1;
                    else
                        l = m+1;
                }
                else if (A[m] < A[l]){
                    if (target <= A[h] && target > A[m])
                        l = m+1;
                    else
                        h = m-1;
                }
                else
                    l++;
            }
            return -1;
        }
    };
  • 相关阅读:
    学生数据增删改查--顺序表
    应用3+2mvc第一次作业
    双色球随机选【代码】
    字符串穷举
    使用nuget发布自己的包
    VS CODE中配置JAVA格式化细节
    反射的理解(含一点xml)
    UdpClient实现udp消息收发
    c#背包问题代码
    利用TcpClient,简单的tcp消息收发
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4444243.html
Copyright © 2011-2022 走看看