zoukankan      html  css  js  c++  java
  • 表现良好时间段


    import java.util.HashMap;
    import java.util.Map;

    /**
    * 给你一份工作时间表 hours,上面记录着某一位员工每天的工作小时数。
    * 我们认为当员工一天中的工作小时数大于 8 小时的时候,那么这一天就是「劳累的一天」。
    * 所谓「表现良好的时间段」,意味在这段时间内,「劳累的天数」是严格 大于「不劳累的天数」。
    * 请你返回「表现良好时间段」的最大长度。
    * <p>
    * 示例 1:
    * 输入:hours = [9,9,6,0,6,6,9]
    * 输出:3
    * 解释:最长的表现良好时间段是 [9,9,6]。
    * <p>
    * 提示:
    * 1 <= hours.length <= 10000
    * 0 <= hours[i] <= 16
    */
    public class _1124_LongestWPI {

    public static void main(String[] args) {
    int[] arr = {6, 9, 9, 6, 0, 6, 6, 9, 9, 9, 9};
    System.out.println(longestWPI(arr));
    }

    public static int longestWPI(int[] hours) {
    if (hours.length == 0) return 0;
    Map<Integer, Integer> map = new HashMap<>(); // key is possible sum in hours array, value is index where that sum appears for the first time
    int maxLen = 0;
    int sum = 0; // sum at index i indicates the sum of hours[0:i] after transformation

    for (int i = 0; i < hours.length; i++) {
    sum += hours[i] > 8 ? 1 : -1; // transform each hour to 1 or -1
    if (sum > 0) { // in hours[0:i], more 1s than -1s
    maxLen = i + 1;
    } else {
    if (!map.containsKey(sum)) {
    map.put(sum, i); // record where the sum appears for the first time
    }
    if (map.containsKey(sum - 1)) { // get the index j where sum of hours[0:j] is sum - 1, so that sum of hours[j+1:i] is 1
    maxLen = Math.max(maxLen, i - map.get(sum - 1));
    }
    }
    }
    return maxLen;
    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    深入理解java虚拟机(7)---线程安全 & 锁优化
    深入理解java虚拟机(6)---内存模型与线程 & Volatile
    java注解框架
    敏捷软件开发---闲话敏捷
    深入理解java虚拟机(5)---字节码执行引擎
    龙应台写给儿子安德烈的信
    wojilu中的路由
    如何使用豆约翰博客备份专家批量下载新浪微博
    haha
    http://www.jsbreakouts.org/---各种html5框架实现打砖块游戏 breakout
  • 原文地址:https://www.cnblogs.com/laydown/p/14737354.html
Copyright © 2011-2022 走看看