How to find missing values in a sequence with PHP?

后端 未结 3 930
甜味超标
甜味超标 2021-01-21 14:02

Suppose you have an array \"value => timestamp\". The values are increasing with the time but they can be reset at any moment.

For example :

$array = arr         


        
3条回答
  •  失恋的感觉
    2021-01-21 14:42

    You can do the following:

    • Keep comparing adjacent array keys. If they are consecutive you do nothing.
    • If they are not consecutive then you check their values, if the value has dropped from a higher value to a lower value, it means there was a reset so you do nothing.
    • If the value has not dropped then it is a case of missing key(s). All the numbers between the two keys(extremes not included) are part of the result.

    Translated in code:

    $array = array( 1 => 6000, 2 => 7000, 3 => 8000, 7 => 9000, 8 => 10000, 
                    9 => 11000,55 => 1000, 56 => 2000, 57 => 3000, 59 => 4000, 
                    60 => 5000,);
    
    $keys = array_keys($array);
    for($i=0;$i

    Working link

提交回复
热议问题