683. K Empty Slots

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: 1
Output: 2
Explanation: In the second day, the first and the third flower have become blooming.

Example 2:

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

Note:

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

这题表述有毛病,day说是1~N,其实应该是0~N-1。
而且flowers[i]定义为第i天,开在x位置。开始以为第i位置,第x天开。
而且还是中间间隔几个空位。
没仔细审题就会出错啊!
奇葩问题描述,做法倒不难,就是理解上容易分歧,耽误时间。
坑!
循环每一天,然后开花,然后检查新开花位置两边距离各多少,更新hashset。

class Solution {
    public int kEmptySlots(int[] flowers, int k) {
        int n = flowers.length;
        boolean[] garden = new boolean[n];
        HashSet<Integer> d = new HashSet<Integer>();
        // iterate through day
        for(int i=0;i<n;i++){
            int x = flowers[i]-1;
            //System.out.println("x: "+x);
            garden[x]=true;
            // iterate through flowers
            int left = 1, right = 1;
            while(x-left>=0){
                if(garden[x-left]) {d.add(left-1);break;}
                left++;
            }
            while(x+right<n){
                if(garden[x+right]) {d.add(right-1);break;}
                right++;
            }
            //System.out.println("left: "+left+" right: "+right);
            if(d.contains(k)) return i+1;
        }
        return -1;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,150评论 0 23
  • 今天复听第一课父母教练修心营 听开营课时我真的是边听边笑,不知道是不是我笑点低,反正我听课感觉像是听相声,真的不是...
    秋儿2017阅读 360评论 0 0
  • 为你 在心里埋下一颗小小的种子 努力的去灌溉 为喜欢的你 做些小事 也会倍感甜蜜呀
    percy0016阅读 232评论 0 0
  • 到了年纪就知道一切无常。天下无不散之宴席,人有生老病死,夫妻可能离散,朋友也可能变成敌人。 眼见他起高楼,眼见他宴...
    江欲行阅读 457评论 2 0
  • 目前还不错的文,就喜欢这种求而不得的哈哈,男主丁言,女主温小良,快点让小良爱上你吧哈哈,可怜的男主,也是个受害者
    悠然逛南山阅读 523评论 0 0