Interview - Find magnitude pole in an array

前端 未结 8 2273
孤独总比滥情好
孤独总比滥情好 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:34

    Interesting question, I am having my own solution in C# which I have given below, read the comments to understand my approach.

    public int MagnitudePoleFinder(int[] A)
    {
        //Create a variable to store Maximum Valued Item i.e. maxOfUp
        int maxOfUp = A[0];
    
        //if list has only one value return this value
        if (A.Length <= 1) return A[0];
    
        //create a collection for all candidates for magnitude pole that will be found in the iteration
        var magnitudeCandidates = new List>();
    
        //add the first element as first candidate
        var a = A[0];
        magnitudeCandidates.Add(new KeyValuePair(0, a));
    
        //lets iterate
        for (int i = 1; i < A.Length; i++)
        {
            a = A[i];
            //if this item is maximum or equal to all above items ( maxofUp will hold max value of all the above items)
            if (a >= maxOfUp)
            {
                //add it to candidate list
                magnitudeCandidates.Add(new KeyValuePair(i, a));
                maxOfUp = a;
            }
            else
            {
                //remote all the candidates having greater values to this item
                magnitudeCandidates = magnitudeCandidates.Except(magnitudeCandidates.Where(c => c.Value > a)).ToList();
            }
        }
        //if no candidate return -1
        if (magnitudeCandidates.Count == 0) return -1;
        else
            //return value of first candidate
            return magnitudeCandidates.First().Key;
    }
    

提交回复
热议问题