美文网首页
683. K Empty Slots

683. K Empty Slots

作者: 冷殇弦 | 来源:发表于2017-09-30 03:48 被阅读0次

    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;
        }
    }
    

    相关文章

      网友评论

          本文标题:683. K Empty Slots

          本文链接:https://www.haomeiwen.com/subject/mwtgextx.html