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

Search for a Range

时间:2015-03-11 10:51:13      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

Search for a Range

 Total Accepted: 36248 Total Submissions: 130885

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm‘s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

MySolution:
int ReturnArray[2]={-1,-1};

int*
searchRange(int A[], int n, int target)
{
    int StartingDex = 0,EndingDex = 0;
    int i;
    int IsFoundTarget = 0;
    int IstheLastElement = 0;
    int IHalf = (int)(n/2)-1;
    /* 0 n/2 n-1 */
    /* 0 n/2 */
    if( IHalf < 0 )
        IHalf = 0;
    if( target >= A[0] && target <= A[IHalf] )
    {
        for( i = 0; i <= IHalf; i++)
        {
            if( target == A[i] && IsFoundTarget == 0 )
            {
                /* found the target */
                IsFoundTarget=1;
                StartingDex = i;
                EndingDex = StartingDex;
                continue;
            }
            else
            {
                if( target == A[i] )
                {
                    EndingDex = i;
                }
                continue;
            }
        }
    }

    /* n/2 n-1 */
    if( target >= A[IHalf] && target <=A[n-1] )
    {
        for( i = IHalf; i <= n-1; i++)
        {
            if( i == n-1 )
                IstheLastElement = 1;
            if( target == A[i] )
            {
                if( IsFoundTarget == 0 )/* StartingDex not found before */
                {
                    IsFoundTarget = 1;
                    StartingDex = i;
                }
                if( IsFoundTarget != 0 || IstheLastElement != 0 )
                {
                    EndingDex = i;
                    continue;
                }
            }
        }
    }

    if( IsFoundTarget == 0 )
    {
        StartingDex = EndingDex = -1;
    }

    ReturnArray[0] = StartingDex;
    ReturnArray[1] = EndingDex;

    return ReturnArray;
}


Result :

Submission Result: Accepted


Search for a Range

标签:

原文地址:http://blog.csdn.net/oimchuan/article/details/44195141

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