码迷,mamicode.com
首页 > 其他好文 > 详细

【Search In Rotated Sorted Array】cpp

时间:2015-04-16 00:59:29      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

题目

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 begin = 0;
        int end = n-1;
        while (begin != end)
        {
            if( begin+1 == end )
            {
                if (A[begin]==target) return begin;
                if (A[end]==target) return end;
                return -1;
            }
            const int mid = (end+begin)/2;
            if (A[mid]==target) return mid;
            if(target<A[mid])
            {
                if(A[begin]<A[mid])
                {
                    if(target>=A[begin])
                    {
                        end = mid-1;
                    }
                    else
                    {
                        begin = mid+1;
                    }
                }
                else
                {
                    end = mid-1;
                }
            }
            else
            {
                if(A[begin]<A[mid])
                {
                    begin = mid+1;
                }
                else
                {
                    if(target<=A[end])
                    {
                        begin = mid+1;
                    }
                    else
                    {
                        end = mid-1;
                    }
                }
            }
        }
        if (A[begin]==target) return begin;
        return -1;
    }
};

 

Tips:

1. 分target与A[mid]大小情况先讨论

2. 由于前半截或后半截至少一个是有序的,再按照这个来分条件讨论

if else代码中有一些逻辑可以合并,但是考虑到保留原始逻辑更容易被理解,就保留现状了

【Search In Rotated Sorted Array】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4430522.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!