Interview - Find magnitude pole in an array

前端 未结 8 2245
孤独总比滥情好
孤独总比滥情好 2021-02-09 15:52

Magnitude Pole: An element in an array whose left hand side elements are lesser than or equal to it and whose right hand side element are greater than or equal to it.

8条回答
  •  暖寄归人
    2021-02-09 16:39

    How about the following code? I think its efficiency is not good in the worst case, but it's expected efficiency would be good.

        int getFirstPole(int* a, int n)
    {
        int leftPole = a[0];
        for(int i = 1; i < n; i++)
        {
            if(a[j] >= leftPole)
            {
                int j = i;
                for(; j < n; j++)
                {
                    if(a[j] < a[i])
                    {
                        i = j+1;  //jump the elements between i and j                   
                        break;
                    }
                    else if (a[j] > a[i])
                        leftPole = a[j];
                }
                if(j == n) // if no one is less than a[i] then return i
                    return i;
            }
        }
        return 0;
    }
    

提交回复
热议问题