Huawei OD Computer-Based Test Algorithm Questions: Unhappy Children

Table of contents

Question part

Interpretation and analysis

Code


Question part

topic unhappy kid
difficulty Disaster
Question description A number of rocking cars have been added to the playground, which are very popular with children. However, each rocking car can only be used by one child at a time. If there is no free rocking car, you need to wait in line or leave directly. In the end, you will not be able to play. The children will be very unhappy.
Please count the number of unhappy children based on their coming and going today.
1. The number of rocking cars is N, and the range is: 1 <= N < 10;
2. Each child corresponds to a code, and the code is a non-repeating number. The coming and going of the children today can be represented by the code: 1 1 2 3 2 3. (If the child has a free rocker before leaving, it means that the child left after playing; the situation of the child playing multiple times is not considered). Number of children ≤ 100.
3. The question ensures that all input data have no abnormalities and the range meets the above instructions.
Enter description First line: Number of rocking carts.
The second line: the coming and going of children.
Output description Returns the number of unhappy children.
Additional information none
------------------------------------------------------
Example
Example 1
enter 1
1 2 1 2
output 0
illustrate In the first row, there is 1 rocker. In the second row, No. 1 comes and No. 2 comes (queuing up). No. 1 goes and No. 2 goes (the rocker is free after No. 1 leaves, so he leaves after playing).
Example 2
enter 1
1 2 2 3 1 3
output 1
illustrate In the first row, there is 1 rocker. In the second row, No. 1 comes and No. 2 comes (queues). No. 2 leaves (leave unhappy). No. 3 comes (queues). No. 1 walks and No. 3 leaves (No. 1 leaves and then shakes the car. There is already free time, so leave after playing).


Interpretation and analysis

Question interpretation :

The first line enters the number of rocking cars.
The numbers in the second line of input appear in pairs. When a number appears for the first time, it means that the child with that number has arrived. When the number appears for the second time, it means that the child has left.

When a friend comes, if there is a rocking car that is idle, play the rocking car; if there is no free rocking car, it will be a party; if the child playing with the rocking car leaves, the child at the front of the queue will play with the free rocking car. Rock the car; if a child in line leaves, the child is unhappy.
This question requires counting the number of unhappy children.

Analysis and ideas :

Before explaining the idea, declare 4 variables:
1. shakeToy, set<Integer>, a collection of integer numbers, initially empty. The collection stores the numbers of children who are playing with the rocker. The maximum size of the collection is the number of rocking cars input by the user.
2. kidQueue, List<Integer>, used to store children who are queuing.
3. allKidSet, Set<Integer>, a collection of integer numbers, initially empty. It is used to store the numbers of all the children who are queuing and playing the rocking car. The data is a collection of shakeToy and kidList.
4. unhappyCnt, an integer number with an initial value of 0, used to count the number of unhappy children.

Traverse the numbers in the input string on the second line. If this number:
1. appears for the first time, then the number does not exist in
shakeToy  or kidList. Determine whether the shakeToy is full at this time (that is, whether its size is equal to the number of shakers). If it is not full, put this number into the shakeToy; if the shakeToy is full, put this number at the end of the kidList. Continue through the next number.
2. The second time it appears, the number must be in shakeToy or kidList. If it is in shakeToy, delete him from shakeToy, and put the number ranked first in kidList (if kidList is not empty) into shakeToy; if it is in kidList, delete it from kidList, indicating that the child is still in the queue. Just leave and increase unhappyCnt by 1. Continue through the next number.
The last counted unhappyCnt is the expected result.

This algorithm only needs to traverse the string once, with a time complexity of O(n) and a space complexity of O(n).


Code

Java code

import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * 不开心的小朋友
 * @since 2023.09.12
 * @version 0.1
 * @author Frank
 *
 */
public class UnhappyKids {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			String input = sc.nextLine();
			int count = Integer.parseInt( input );
			input = sc.nextLine();
			String[] numbers = input.split( " " );
			processUnhappyKids( count, numbers );
		}
		
	}
	
	private static void processUnhappyKids( int count, String numbers[] )
	{
		Set<Integer> shakeToy = new HashSet<Integer>();
		List<Integer> kidQueue = new ArrayList<Integer>();
		Set<Integer> allKidSet = new HashSet<Integer>();
		int unhappyCnt = 0;
		
		for( int i = 0; i < numbers.length; i ++ )
		{
			int currentNum = Integer.parseInt( numbers[i] );
			
			// 如果首次出现
			if( !allKidSet.contains( currentNum ))
			{
				// 摇摇车满了
				if( shakeToy.size() >= count )
				{
					kidQueue.add( currentNum );					
				}else
				{
					shakeToy.add( currentNum );
				}		
				allKidSet.add( currentNum );
			}else  // 第二次出现,则在排队或者在玩游戏中
			{
				
				if( shakeToy.contains( currentNum ) )
				{
					shakeToy.remove( currentNum );
					if( kidQueue.size() > 0 )
					{
						int queueFirst = kidQueue.get( 0 );
						shakeToy.add( queueFirst );
						kidQueue.remove( 0 );
					}					
				}else  // 在排队中离开,不高兴
				{	
					// 删除 Object,而不是 index,此处要转换成 Integer。
					kidQueue.remove( (Integer) currentNum );
					unhappyCnt ++;
				}
				allKidSet.remove( currentNum );
			}
		}
		System.out.println( unhappyCnt );
	}

}

JavaScript code

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void async function() {
    while (line = await readline()) {
        var count = parseInt(line);
        line = await readline();
        var numberArr = line.split(" ");
        processUnhappyKids(count, numberArr);
    }
}();

function processUnhappyKids(count, numbers) {
    var shakeToy = new Set();
    var kidQueue = new Array();
    var allKidSet = new Set();
    var unhappyCnt = 0;

    for (var i = 0; i < numbers.length; i++) {
        var currentNum = parseInt(numbers[i]);

        // 如果首次出现
        if (!allKidSet.has(currentNum)) {
            // 摇摇车满了
            if (shakeToy.size >= count) {
                kidQueue.push(currentNum);
            } else {
                shakeToy.add(currentNum);
            }
            allKidSet.add(currentNum);
        } else // 第二次出现,则在排队或者在玩游戏中
        {

            if (shakeToy.has(currentNum)) {
                shakeToy.delete(currentNum);
                if (kidQueue.length > 0) {
                    var queueFirst = kidQueue.shift();
                    shakeToy.add(queueFirst);
                }
            } else // 在排队中离开,不高兴
            {
                var idx = kidQueue.indexOf( currentNum );
                kidQueue.splice( idx, 1 );
                unhappyCnt++;
            }
            allKidSet.delete(currentNum);
        }
    }
    console.log(unhappyCnt);
}

(over)

Guess you like

Origin blog.csdn.net/ZiJinShi/article/details/132825605