Huawei OD Computer-based Test Algorithm Questions: Building Blocks Game with Same Numbers 1

Question part

topic Same number building blocks game 1
difficulty easy
Question description Xiaohua and Xiaowei learn mathematics together by playing building blocks.
They have many building blocks, and each block has a number on it. The numbers on the blocks may be the same.
Xiaohua randomly arranges some building blocks next to each other in a row, and asks Xiaowei to find the two building blocks with the same number and the furthest position in the row of building blocks, and calculate their distance.
Xiaowei asks you to help solve this problem.
Enter description The input in the first line is N, which represents the total number of blocks that Xiaohua has lined up in a row.
Each of the next N lines contains a number, which represents the numbers on the blocks that Xiaohua has arranged in a row.
Output description The position of the building blocks with the same number is the furthest distance;
If all the building block numbers are different, please return.
Additional information none
------------------------------------------------------
Example
Example 1
enter 5
1
2
3
1
4
output 3
illustrate Explain that there are 5 building blocks in total, the first building block and the 4th building block have the same number, and their distance is 3.
Example 2
enter 2
1
2
output -1
illustrate There are 2 blocks, and no block has the same number, -1 is returned.


Interpretation and analysis

Item explanation

gives a sequence of numbers. If these numbers are not the same, -1 is returned. If there are the same numbers, calculate the farthest distance of each identical number (for example, if there are three 5s in a set of numbers, you need to calculate the distance between the first 5 and the third 5, because they are the farthest).
Finally, output the maximum value among all the farthest distances.

Analysis Yoshiro

The implementation steps are as follows:
1. Initialize and put the input number into the array numArr.
2. Create a Map (set to numMap), whose key is the numeric value in numArr, and value is an array containing 2 int elements (set to itemArr), where item[0] is the subscript of the first occurrence of key in the array numArr, and item[1] is the subscript of the last occurrence of key in the array numArr.
3. Traverse the array numArr, and set the current element index to i. Determine whether numArr[i] exists in numMap. If it does not exist, add an element to numMap. The key is i and the value is an array item containing 2 elements (the initial values ​​are both 0), where item[0] = i. If 
numArr[i] exists in numMap, it means that item[0] of value has been assigned a value, and item[1] is assigned the value i at this time.
4. After traversing the array numArr, numMap records all the appearing numbers, as well as the first and last appearing positions of each number (when a number only appears once, then The value of the last occurrence is 0). Traverse numMap, calculate the maximum value of item[1] - item[0], and set it as maxValue. If maxValue is less than or equal to 0, meaning there are no duplicate numbers, -1 is returned. Otherwise, output maxValue.

The time complexity of this algorithm is O(n) and the space complexity is O(n).


Code

Java code

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;

/**
 *  相同数字的积木游戏1
 * 
 * @since 2023.11.02
 * @version 0.1
 * @author Frank
 *
 */
public class BlockMaxDistance {

    public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	while (sc.hasNext()) {
	    
	    String input = sc.nextLine();
	    int count = Integer.parseInt( input );
	    
	    int[] numArr = new int[count];
	    for( int i = 0; i < count; i ++ )
	    {
		input = sc.nextLine();
		int value = Integer.parseInt( input );
		numArr[i] = value;
	    }
	    processBlockMaxDistance( numArr );

	}

    }

    private static void processBlockMaxDistance(int[] numArr) {
	Map<Integer, int[]> numMap = new HashMap<Integer, int[]>();
	for( int i = 0; i < numArr.length; i ++ )
	{
	    Integer key = numArr[i];
	    int[] item = numMap.get( key );
	    if( item == null )
	    {
		item = new int[2];
		item[0] = i;
		numMap.put( key,  item );
	    }else
	    {
		item[1] = i;
	    }
	}
	
	int maxDistance = 0;
	for( Iterator<Integer> iter = numMap.keySet().iterator(); iter.hasNext();)
	{
	    Integer key = iter.next();
	    int[] item = numMap.get( key );
	    int distance = item[1] - item[0];
	    if( distance > maxDistance )
	    {
		maxDistance = distance;
	    }
	}
	if( maxDistance == 0 )
	{
	    maxDistance = -1;
	}
	System.out.println( maxDistance );
    }

}

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

        var numArr = new Array();
        for (var i = 0; i < count; i++) {
            line = await readline();
            var value = parseInt(line);
            numArr[i] = value;
        }
        processBlockMaxDistance(numArr);
    }
}();

function processBlockMaxDistance(numArr) {
    var numMap = new Map();
    for (var i = 0; i < numArr.length; i++) {
        var key = numArr[i];
        var item = numMap.get(key);
        if (item == null) {
            item = [0, 0];
            item[0] = i;
            numMap.set(key, item);
        } else {
            item[1] = i;
        }
    }

    var maxDistance = 0;
    for ( let [key, value] of numMap ) {
        var item = value;
        var distance = item[1] - item[0];
        if (distance > maxDistance) {
            maxDistance = distance;
        }
    }
    if (maxDistance == 0) {
        maxDistance = -1;
    }
    console.log(maxDistance);
}

(over)

おすすめ

転載: blog.csdn.net/ZiJinShi/article/details/134165231