How would you get the index of the lowest value in an int array?

前端 未结 5 1777
旧巷少年郎
旧巷少年郎 2020-12-28 16:45

Considering that this is a very basic task, I could not think of an appropriately easy way to do it. How would you get the index of the lowest value in an int array? Using L

5条回答
  •  时光说笑
    2020-12-28 17:23

    LINQ probably isn't the best solution for this problem, but here's another variation that is O(n). It doesn't sort and only traverses the array once.

    var arr = new int[] { 3, 1, 0, 5 };
    int pos = Enumerable.Range(0, arr.Length)
        .Aggregate((a, b) => (arr[a] < arr[b]) ? a : b); // returns 2
    

    Update: Answering the original question directly, this is how I would do it:

    var arr = new int[] { 3, 1, 0, 5 };
    int pos = 0;
    for (int i = 0; i < arr.Length; i++)
    {
        if (arr[i] < arr[pos]) { pos = i; }
    }
    // pos == 2
    

    No, it doesn't use LINQ. Yes, it is more than one line. But it is really simple and really fast. Make it into a tiny little method and call it from anywhere on a single line: pos = FindMinIndex(arr);

提交回复
热议问题