Java 华为真题-新员工座位安排

需求:

工位由序列F1,F2…Fn组成,Fi值为0、1或2。其中0代表空置,1代表有人,2代表障碍物.
  1、某一空位的友好度为左右连续老员工数之和
  2、为方便新员工学习求助,优先安排友好度高的空位给出工位序列,求所有空位中友好度的最大值

输入描述:
     第一行为工位序列: F1.F2…Fn组成,1<=n<=100000,Fi值为0、1或2。其中0代表空置,1代码有人,2代表障碍物其中0代表空置,1代码有人,2代表障碍物。
输出描述:
    所有空位中友好度的最大值。如果没有空位,返回0 

示例1
输入:
0 1 0
输出:
1

说明:
第1个位置和第3个位置,友好度均为1

示例2
输入:
1 1 0 1 2 1 0
输出:
3

说明:
第3个位置友好度为3。因障碍物隔断,左边得2分,右边只能得1分

编码:

public class TesEmployee {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("输入工位序列:");
        String[] postion = sc.nextLine().split(" ");
        //字符串数组转换成整数数组
        int[] arr = Arrays.asList(postion).stream().mapToInt(Integer::parseInt).toArray();

        //使用map存放
        Map<Integer, Integer> mapLeft = new HashMap<>();
        Map<Integer, Integer> mapRight = new HashMap<>();

        //调用方法
        saveMap(arr,0,mapLeft);
        saveMap(arr,1,mapRight);

//        所有空位中友好度的最大值
        int max=getMax(mapLeft,mapRight);
        System.out.println(max);

    }

    /**
     * 计算所有空位中友好度的最大值
     * @param map1
     * @param map2
     * @return
     */
    public static int getMax(Map<Integer, Integer> map1,Map<Integer, Integer> map2){
       int max=0;
        for (Integer key:map1.keySet()
             ) {
            Integer  value=map1.get(key)+map2.get(key);
            //进行比较
            max=Math.max(max,value);
        }
        return max;
    }

    /**
     * 正向遍历一遍,反向遍历一遍,遇到0,就把连续1的值记录下来
     * @param arr
     * @param flag
     * @param map
     */
    public static void saveMap(int[] arr, int flag, Map<Integer, Integer> map) {
        //累计1的和
        int sum = 0;
        if (flag == 0) {  //如果是正向遍历, 工位是1的,sum就加1,工位是0,则sum为0
            //循环
            for (int i = 0; i < arr.length; i++) {
                //判断
                if (arr[i] == 1) {
                    sum++;  //累计和
                } else if (arr[i] == 0) {
                    map.put(i, sum);
                    sum = 0; //重置sum为0
                } else {
                    sum = 0; //重置sum为0
                }
            }
        } else {  //如果是反向遍历,同理;
            //循环
            for (int i = arr.length - 1; i >= 0; i--) {
                //判断
                if (arr[i] == 1) {
                    sum++;  //累计和
                } else if (arr[i] == 0) {
                    map.put(i, sum);
                    sum = 0; //重置sum为0
                } else {
                    sum = 0; //重置sum为0
                }
            }
        }

    }


}

效果:

猜你喜欢

转载自blog.csdn.net/hlx20080808/article/details/133346490