Find min value in array > 0

前端 未结 7 1950
夕颜
夕颜 2021-02-07 05:49

I am looking to find the lowest positive value in an array and its position in the list. If a value within the list is duplicated, only the FIRST instance is of interest. This i

相关标签:
7条回答
  • the complicated / algorithmic way:

    int min = array[0], i = 1
    list smallest //list of indexes of the smallest element 
    
    // find the first element greater than 0
    while (min <= 0 and i < array.length) {
        min = array[i]
        i++
    }
    
    // find the first instance of the smallest element greater than 0
    while (i < array.length) {
        if (array[i] < min and array[i] > 0) {
            clear the list
            min = array[i]
            list.append(i)
        }
        else if (array[i] == min) {
            list.append(i)
        }
        i++;
    }
    

    the first instance of the smallest element greater than 0 is now the first element that you added to the list.

    edit: you'll also have a list of every index of the smallest value. Some simple checks can tell you if there are no elements in the array greater than 0, or if the list is empty, etc.

    0 讨论(0)
提交回复
热议问题