Find the minimum value and its location among multiple numbers (with repetition)

Find the minimum value among the given numbers, and get the position of the minimum value in the number.

  1. When there are no duplicate values ​​in multiple numbers, it is only necessary to traverse the list storing these numbers;
  2. When there are repeated values ​​in multiple numbers, you can add a new list MinIndexto store the position of the current minimum value. When the minimum value changes during the traversal process, you need to clear MinIndexand add the position of the new minimum value MinIndexto . When the traversal process When there is a repeated value of the minimum value in , the position of the value needs to be filled MinIndexin .
public static List<int> FindMin(List<float> NumList)
{
    
    
    List<int> MinIndex = new List<int>() {
    
     0 };
    float MinNum = NumList[0];

    for (int i = 1; i < NumList.Count; i++)
    {
    
    
        //如果最小值出现变化,则更改最小值,
        //并清除记录最小值位置的List,并将当前值的位置添加进去
        if (MinNum > NumList[i])
        {
    
    
            MinNum = NumList[i];
            MinIndex.Clear();
            MinIndex.Add(i);
        }
        //如果出现重复值,也将当前值的位置添加到记录最小值位置的List
        else if (MinNum == NumList[i])
        {
    
    
            MinIndex.Add(i);
        }
    }
    
    //当最小值出现重复时,记录最小值位置的List中将会有多个数字
    //如果只需要一个最小值位置,可以对该List进行随机排序,然后去List[0]即可
    if (MinIndex.Count > 1)
    {
    
    
        System.Random rand = new System.Random();
        List<int> RandList = new List<int>();
        foreach (int i in MinIndex)
        {
    
    
            RandList.Insert(rand.Next(RandList.Count), i);
        }

        return RandList;
    }
    else
    {
    
    
        return MinIndex;
    }
}

Guess you like

Origin blog.csdn.net/qq_33021529/article/details/125928227