Obtain the index of the maximum element

前端 未结 9 1568
梦谈多话
梦谈多话 2020-12-28 15:03

Given such a list:

        List intList = new List();
        intList.Add(5);
        intList.Add(10);
        intList.Add(15);
                


        
9条回答
  •  春和景丽
    2020-12-28 15:33

    I can't improve on Jon Skeet's answer for the general case, so I am going for the 'high performance' prize in the specific case of a list of ints.

    public static class Extensions
    {
        public static int IndexOfMaximumElement(this IList list)
        {
            int size = list.Count;
    
            if (size < 2)
                return size - 1;
    
            int maxValue = list[0];
            int maxIndex = 0;
    
            for (int i = 1; i < size; ++i)
            {
                int thisValue = list[i];
                if (thisValue > maxValue)
                {
                    maxValue = thisValue;
                    maxIndex = i;
                }
            }
    
            return maxIndex;
        }
    

提交回复
热议问题