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

[leetcode]Search in Rotated Sorted Array

时间:2014-11-23 16:04:30      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

问题描述:

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.


基本思想:

此题很简单,最笨的方法就是一个一个找,如果好一点,可以设定一些条件进行剪枝。


代码:

int search(int A[], int n, int target) {  //C++
        if(n < 0)
            return -1;
        if(n == 1)
            if(A[0] == target)
                return 0;
            else return -1;
        
        if(A[0] == target)
            return 0;
        for(int i = 1; i < n; i++)
        {
            if(A[i] < A[i-1])
            {
                if(A[i] > target || A[i-1] < target || target > A[n-1])
                return -1;
            }
            if(A[i] == target )
                return i;
        }
        return -1;
    }


[leetcode]Search in Rotated Sorted Array

标签:leetcode   算法   

原文地址:http://blog.csdn.net/chenlei0630/article/details/41410851

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