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

Search in Rotated Sorted Array

时间:2014-11-27 14:33:08      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

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.


连着三个题都好简单,差不多的思路,lucky……

#include<stdio.h>

int search(int A[], int n, int target) {
    int i,j,tmp;
    for(i=0;i<n-1;i++){
        if((A[i])>A[i+1]) break;
    }
    tmp=i;
    if(target>=A[0]){
        i=0;
        j=tmp;
    }
    else {
        i=tmp+1;
        j=n-1;
    }
    while(i<=j){
        if(A[(i+j)/2]==target) return (i+j)/2;
        if(A[(i+j)/2]>target) j--;
        else i++;
    }
    return -1;
}


Search in Rotated Sorted Array

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://blog.csdn.net/uj_mosquito/article/details/41545089

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