Leetcode PHP题解--D50 933. Number of Recent Calls


D50 933. Number of Recent Calls

题目链接

933. Number of Recent Calls

题目分析

这个题目说实在的,看得我一脸蒙蔽。

返回自3000毫秒到现在为止ping的次数(包括当前ping)。

ping函数时,传入的参数t为当前ping的毫秒数。

思路

其实是说,返回前3000毫秒内ping的次数。

把每次ping的毫秒数存起来,然后往回找3000毫秒内的ping。

即,给当前ping次数加1,直到当前毫秒数减前面ping的毫秒数大于3000。

最终代码

<?php
class RecentCounter {
    public $pings = [];
    public $head = 0;

    function __construct() {

    }
    function ping($t) {
        if(is_null($t)){
            return null;
        }
        $this->pings[] = $t;

        while(($this->pings[count($this->pings)-1]-$this->pings[$this->head])>3000){
            $this->head++;
        }
        return count($this->pings)-$this->head;
    }
}
/**
 * Your RecentCounter object will be instantiated and called as such:
 * $obj = RecentCounter();
 * $ret_1 = $obj->ping($t);
 */ 

若觉得本文章对你有用,欢迎用爱发电资助。


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Leetcode PHP题解--D49 821. Shortest Distance to a Character

>> 下一篇: Leetcode基础刷题之PHP解析( 144. 145)