【问题标题】:Find Max Number of Employees to Attend Training查找参加培训的最大员工人数
【发布时间】:2022-07-14 05:53:52
【问题描述】:

在接下来的 10 天内将进行两次为期一天的培训课程。有 N 名员工(编号为 0 到 N-1)愿意参加。每位员工都提供了一份清单,说明他们可以在接下来的 10 天中的哪一天参加培训。员工偏好表示为字符串数组。 E[K] 是一个字符串,表示第 K 个员工能够参加培训的天数。 培训日期尚未确定。至少在两个预定日期之一期间可以参加的最大员工人数是多少?

写一个函数:

class Solution { public int solution(String[] E); }

编写一个函数,给定一个由 N 个字符串组成的数组 E,表示每个员工的可用天数,该函数将返回在两个预定天数中的至少一个天可以参加的最大员工数。

例子:

  1. 给定 E = ["039", "4", "14", "32", "", "34", "7"],答案是 5。例如,可以通过在第 3 天和第 4 天。这样,第 0、1、2、3 和 5 号员工将参加培训。
  2. 给定 E = ["801234567", "180234567", "0", "189234567", "891234567", "98", "9"],答案是 7。例如可以通过运行训练来实现在第 0 天和第 9 天。这样员工都将参加培训。
  3. 给定 E = [“5421”、“245”、“1452”、“0345”、“53”、“345”],答案是 6。例如,可以通过在第 5 天进行一次训练来实现. 这样所有员工都会参加培训。

我正在使用以下解决方案:

class Solution {
    public int solution(String[] E) {
        int i = 0;
        boolean arr[] = new boolean[E.length];
        
        for (String s: E){
            boolean flag=true;
            for (char ch: s.toCharArray())
                if( Character.compare(ch,'N')==0)
                        flag=false;
            arr[i++]=flag;
        }

        int count=0;
        int totalcount=0;
        for(boolean ch: arr){
            if(ch){
               count++;
               if(count>totalcount)
                    totalcount=count;
             } else
                count=0;
        }
        return totalcount;
    }
}

但是第一个测试用例失败了。有人知道为什么吗?

【问题讨论】:

  • 添加您可能想出的任何方法,以及您面临的具体挑战
  • 我添加了我的解决方案和问题。谢谢
  • 你能解释一下你的方法吗?
  • 这是 Maximum-coverage problem 在特定情况下 k=2
  • 您必须描述您的解决方案如何尝试解决问题。现在,它只是一堆未注释的代码。还要描述您尝试的解决方案与正确解决方案不同的点。

标签: algorithm max set-cover


【解决方案1】:

实现的步骤我用了Multiple steps来解决问题,下面是步骤。

  1. 步骤1:将每个String转换为Integer List,并将每个整数列表添加到以Key为索引的Map对象中,Value是一个创建的List

  2. 第 2 步:迭代地图以找出每个列表中重复的天数并计算这些日期的计数。

  3. Step3:找出每个员工在输入字符串中重复出现的日期。

最后你得到实际计数

    static int solutions(String[] input) {
        HashMap<Integer, List<Integer>> map = new HashMap<>();
        int index = 0;
        for(String s : input) {
            List<Integer> list = new ArrayList<>();

            for (int i =0; i < s.length(); i ++) {
                int k = Integer.parseInt(String.valueOf(s.charAt(i)));
                    list.add(k);
            }
            map.put(index, list);
            ++index;
        }

        Map<Integer, Long> counts = new HashMap<>();
       for(List<Integer> inputEntry : map.values()) {
           for(Integer n: inputEntry) {
               Long c = counts.get(n);
               if (c == null) {
                   c =0L;
               }
               counts.put(n, c+1);
           }
       }
        Iterator<Long> it = counts.values().iterator();
       while (it.hasNext()) {
           Long c = it.next();
           if (c == 1L) {
               it.remove();
           }
       }
       //int mCount = 0;
       Map<String, Integer> map1 = new HashMap<>();
       Set<Integer> set = counts.keySet();
       for (String s: input) {
           for (int a : set) {
               if (s.contains(a+"")) {
                   map1.put(s, a);
               }
           }
       }
        return (int) map1.entrySet().stream().count();
    }

【讨论】:

    【解决方案2】:
    public static int solution(String[] E) {
    
        /*
         * Step 1.
         *
         * For convenience, let's combine the employee index and their available days.
         * For example, if the input is ["1", "01", "98"], the daysPerEmployee is {0="1", 1="01", 2="98"].
         */
        Map<String, String> daysPerEmployee = new HashMap<>();
        for (int employerIndex = 0; employerIndex < E.length; employerIndex++) {
            String employer = String.valueOf(employerIndex);
            String employerAvailableDays = E[employerIndex];
            daysPerEmployee.put(employer, employerAvailableDays);
        }
    
        System.out.println(daysPerEmployee);
    
        /*
         * Step 2.
         *
         * Let's find out which employees are available per day.
         *
         * For example, if the input is ["1", "01", "98"], the employeesAvailablePerDay is
         * {0=["1"], 1=["0", "1"], 2=[], 3=[], 4=[], 5=[], 6=[], 7=[], 8=["2"], 9=["2"]}.
         *
         * On day 0 only the employee 1 is available;
         * On day 1 employees 0 and 1 are available;
         * No employees are available on day 2;
         * ...
         * On day 9 only employee 2 is available.
         */
        Map<Integer, Set<String>> employeesAvailablePerDay = new HashMap<>();
        for (int dayIndex = 0; dayIndex < 10; dayIndex++) {
            String day = String.valueOf(dayIndex);
            Set<String> employers = daysPerEmployee
                    .entrySet().stream()
                    .filter(e -> e.getValue().contains(day)) // find all employees that are available on dayIndex
                    .map(Map.Entry::getKey) // map entries to employee index
                    .collect(Collectors.toSet());
    
            employeesAvailablePerDay.put(dayIndex, employers);
        }
    
        System.out.println(employeesAvailablePerDay);
    
        /*
         * Step 3.
         *
         * Now the goal is to find two sets (there are two scheduled dates) of employees
         * which combined contains as many employees as possible.
         *
         * For that, we can start combining employees available on day 0 with employees that are
         * available on the remaining days: 1, 2,.., 9. Then combine available employees on day 2
         * with employees available on the remaining days: 2, 3,..,9. And so on:
         * Day 0 employees: combine with Day 1, 2, 3, 4, 5, 6, 7, 8, 9 employees
         * Day 1 employees: combine with Day 2, 3, 4, 5, 6, 7, 8, 9 employees
         * Day 2 employees: combine with Day 3, 4, 5, 6, 7, 8, 9 employees
         * Day 3 employees: combine with Day 4, 5, 6, 7, 8, 9 employees
         * Day 4 employees: combine with Day 5, 6, 7, 8, 9 employees
         * Day 5 employees: combine with Day 6, 7, 8, 9 employees
         * Day 6 employees: combine with Day 7, 8, 9 employees
         * Day 7 employees: combine with Day 8, 9 employees
         * Day 8 employees: combine with Day 9 employees
         *
         * Every time when you merge two sets of available employees get the size of combined set.
         * Memorize it if it's larger than the size of the previous set.
         *
         * For example, let's say employeesAvailablePerDay is
         * {0=["1"], 1=["0", "1"], 2=[], 3=[], 4=[], 5=[], 6=[], 7=[], 8=["2"], 9=["2"]}.
         *
         * Combine set 0=["1"] and set 1=["0", "1"]. The result is ["0", "1"]. The size is 2.
         * It's the maximum number of available employees so far -> max=2
         *
         * Combine set 0=["1"] and 2=[]. The result is ["1"]. The size is 1. 1 < max. Let's continue.
         *
         * Combine set 0=["1"] and 9=["2"]. The result is ["1", "2"]. The size is 2. 2 == max. Let's continue.
         *
         * ...
         *
         * Let's start combining sets starting from 1=["0", "1"]:
         * Combine 1=["0", "1"] and 2=[] -> ["0", "1"]. The size is 2. 2 == max. Let's continue.
         * Combine 1=["0", "1"] and 3=[] -> ["0", "1"]. The size is 2. 2 == max. Let's continue.
         * ...
         * Combine 1=["0", "1"] and 9=["2"] -> ["0", "1", "2"]. The size is 3. 3 > max -> max = 3.
         * ...
         * End of the loop. We iterated over all available days. Max size of two combined sets is 3.
         */
        Set<String> maximumAvailableEmployees = new HashSet<>();
        for (int dayOne = 0; dayOne < employeesAvailablePerDay.keySet().size(); dayOne++) {
            var dayOneAvailableEmployees = employeesAvailablePerDay.get(dayOne);
            for (int dayTwo = dayOne + 1; dayTwo < employeesAvailablePerDay.keySet().size(); dayTwo++) {
                Set<String> dayTwoAvailableEmployees = employeesAvailablePerDay.get(dayTwo);
    
                Set<String> employees = new HashSet<>();
                employees.addAll(dayOneAvailableEmployees);
                employees.addAll(dayTwoAvailableEmployees);
    
                if (employees.size() > maximumAvailableEmployees.size()) {
                    maximumAvailableEmployees = employees;
                }
            }
        }
    
        return maximumAvailableEmployees.size();
    }
    

    【讨论】:

    • 使用solution() 之类的名称,函数需要doc comment。冗长。清晰的代码 cmets!
    • 是否可以将此代码转换为javascript。
    【解决方案3】:
    def solution(E):
      # write your code in Python 3.6
    
      modified_input = []
      days_map = {str(i): {"count": 0, "employee": []} for i in range(0, 10)}
    
      for e in E:
          temp = []
          for j in e:
              temp.append(j)
          modified_input.append(sorted(temp))
    
      for index, value in enumerate(modified_input):
          for days in value:
              days_map[days]["employee"].append(index)
              days_map[days]["count"] += 1
    
      employee = [i for i in range(len(E))]
      for i in range(0, 10):
          if set(employee) == set(days_map[str(i)].get("employee")):
              return len(employee)
    
      day_value = list(days_map.values())
      max_emp = 0
      for emp in range(len(day_value)):
          empl_1 = day_value[emp].get("employee")
          for _emp in range(1, len(day_value)):
              empl_2 = day_value[_emp].get("employee")
              all_emp = empl_1 + empl_2
              if len(set(all_emp)) > max_emp:
                  max_emp = len(set(all_emp))
    
      return max_emp
    

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    • 这段代码是否可以用 JavaScript 重写。
    【解决方案4】:
    int solution(vector<string> &E) {
        int n = E.size();
        unordered_map<int, vector<int> > m2;
        for(int i=0; i<n; i++) {
            int len = E[i].length();
            for(int j=0; j<len; j++) {
                int c = E[i][j] - '0';
                m2[c].push_back(i);
            }
        }
        int ans = 0;
        for(int i=0; i<10; i++) {//making union of all combination of two days
            for(int j=i+1; j<10; j++) {
                int size1 = m2[i].size();
                int size2 = m2[j].size();
                vector<int> v(size1 + size2);
                int size = set_union(m2[i].begin(), m2[i].end(), 
                                     m2[j].begin(), m2[j].end(), v.begin())
                           - v.begin();
                ans = max(ans, size);
            }
        }
        return ans;
    }
    

    【讨论】:

      【解决方案5】:

      对于E 的每个元素,您的代码根据出现的不同于'N' 的字符设置flag,并将flag 存储在arr 中。
      它继续计算在这十天中的任何一天都没有声称不可用的员工。
      要求的结果是在至少两个预定日期之一期间可以参加的最大员工人数:几乎不相关。

      【讨论】:

        【解决方案6】:

        公共 int 解决方案(String[] E) {

            StringBuilder s = new StringBuilder();
            
            Arrays.stream(E).forEach(x->s.append(x));
            
            Map<Character, Long> trainingPreferenceCount = s.chars().mapToObj(x->(char)x)
                                                   .collect(Collectors.groupingBy(x->x,Collectors.counting()));
            
            trainingPreferenceCount.entrySet().removeIf(x -> x.getValue() == 1);
        
            int employeeCount = 0;
            for (String employeePreference : E) {
                for (char training : trainingPreferenceCount.keySet()) {
                    if (employeePreference.contains(training + "")) {
                        employeeCount++;
                        break;
                    }
                }
            }
            return employeeCount;
        }
        

        【讨论】:

          猜你喜欢
          • 2011-07-07
          • 1970-01-01
          • 2010-10-28
          • 2021-02-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-05
          相关资源
          最近更新 更多