博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode 683. K Empty Slots
阅读量:7306 次
发布时间:2019-06-30

本文共 1559 字,大约阅读时间需要 5 分钟。

Problem:

There is a garden with N slots. In each slot, there is a flower. The N flowers will bloom one by one in N days. In each day, there will be exactly one flower blooming and it will be in the status of blooming since then.

Given an array flowers consists of number from 1 to N. Each number in the array represents the place where the flower will open in that day.

For example, flowers[i] = x means that the unique flower that blooms at day i will be at position x, where i and x will be in the range from 1 to N.

Also given an integer k, you need to output in which day there exists two flowers in the status of blooming, and also the number of flowers between them is k and these flowers are not blooming.

If there isn't such day, output -1.

Example 1:

Input: flowers: [1,3,2]k: 1Output: 2Explanation: In the second day, the first and the third flower have become blooming.

Example 2:

Input: flowers: [1,2,3]k: 1Output: -1

Note:

  1. The given array will be in the range [1, 20000].

Solution:

  谷歌的中频题,好好分析下。这道题的核心还是滑动窗口,不过和传统的滑动窗口不太一样,首先用一个数组days[i] = t记录第i+1个位置的花在第t天开放,就是说数字大的就是花放的时间晚,所以说除了首尾两个数字,中间的k个数字都要大于首尾两个数字即可。若在days[left]和days[right]中发现了某个数比两端小,就说明这个位置的花开得比较早,因此以该处为起点进行窗口滑动,如果到了right的位置仍然没有发现较小值,说明left和right是满足要求的,那么就把days[left]和days[right]中的较大值和结果比较取较小值即可。这道题的难点在于滑动窗口的合理使用,flowers数组的转换其实应该可以想到,滑动窗口的思想是重点。

Code:

 

1 class Solution { 2 public: 3     int kEmptySlots(vector
& flowers, int k) { 4 vector
days(flowers.size()); 5 for(int i=0; i

 

转载于:https://www.cnblogs.com/haoweizh/p/10244622.html

你可能感兴趣的文章
HBase Block Cache的重要实现细节和In-Memory Cache的特点
查看>>
用shell脚本实现自动分区
查看>>
我的友情链接
查看>>
见鬼?粉碎移动硬盘数据导致两年Windows8.1奔溃了!
查看>>
iSCSI+GFS共享存储的实现
查看>>
iOS 用到的宏
查看>>
套接字地址结构
查看>>
读书笔记之 将所有增强for语句的循环变量声明为final类型
查看>>
简要的可行性分析报告(1)
查看>>
ThinkSNS受邀请参加OSC(开源中国)源创会成都站
查看>>
Python实现简单的用户登录
查看>>
【持续更新】常用的JQuery 插件汇总
查看>>
设计模式中的设计原则之最小知识原则(Least Knowledge Principle - LKP)
查看>>
张鑫旭:说说CSS学习中的瓶颈(个人觉得对突破技术瓶颈都有思想上的指导作用)...
查看>>
初始化参数列表
查看>>
CentOS 7.x设置自定义开机启动,添加自定义系统服务
查看>>
掌握这些小技巧,让你的电脑一点都不卡,速度超级快
查看>>
周鸿在360新员工入职培训上的讲话
查看>>
说说美国的数据中心
查看>>
1、安装、配置、连接Openfiler
查看>>