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;
        }
    };
  • 相关阅读:
    Java基本语法(一)
    JAVA菜鸟入门HelloWorld
    python 练习题-质数
    python 字符串转运算符
    python 提取不重复的整数
    python 句子逆序
    python 数字颠倒
    python 字符个数统计
    python 练习题-计算字符个数
    python int型正整数在内存中存储为1的个数
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4444243.html
Copyright © 2011-2022 走看看