华为OD机试 - 积木最远距离(Python/JS/C/C++ 2024 E卷 100分)

embedded/2024/10/19 7:29:48/

在这里插入图片描述

华为OD机试 2024E卷题库疯狂收录中,刷题点这里

专栏导读

本专栏收录于《华为OD机试真题(Python/JS/C/C++)》。

刷的越多,抽中的概率越大,私信哪吒,备注华为OD,加入华为OD刷题交流群,每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新,全天CSDN在线答疑。

一、题目描述

小华和小薇一起通过玩积木游戏学习数学。

他们有很多积木,每个积木块上都有一个数字,积木块上的数字可能相同。

小华随机拿一些积木块并排成一排,请你帮她找到这排积木中相同数字且所处位置最远的2块积木,计算它们的距离,小薇请你帮忙着地解决这个问题。

二、输入描述

第一行输入为N,表示小华排成一排的积木总数。

接下来N行每行一个数字,表示小华排成一排的积木上数字。

三、输出描述

相同数字的积木块位置最远距离;如果所有积木块的数字都不相同,请返回-1。

备注

0 <= 积木上的数字 < 109

1 <= 积木长度 <= 105

四、测试用例

测试用例1:

1、输入

5
1
2
3
1
4

2、输出

3

3、说明

共有5个积木,第1个和第4个积木数字相同,其距离为3。

测试用例2:

1、输入

2
1
2

2、输出

-1

3、说明

共有两个积木,没有积木数字相同,返回-1。

测试用例3:

1、输入

6
5
1
5
2
5
3

2、输出

4

3、说明

数字5在索引0、2、4出现。最大距离是4 - 0 = 4。

五、解题思路

为了找到一排积木中相同数字且位置最远的两块积木,我们可以采用以下步骤:

  1. 遍历积木序列:我们需要遍历整个积木序列,记录每个数字第一次出现的位置。
  2. 记录第一次出现的位置:使用一个哈希表(HashMap)来存储每个数字第一次出现的索引位置。
  3. 计算距离:当我们再次遇到已经存在于哈希表中的数字时,计算当前索引与第一次出现的索引之间的距离,并更新最大距离。
  4. 输出结果:遍历完成后,如果找到了至少一对相同数字的积木,输出最大的距离;否则,输出-1。

这种方法的时间复杂度为O(N),适用于N高达10^5的情况。

六、Python算法源码

python"># 导入必要的模块
import sysdef main():# 读取输入N = int(sys.stdin.readline())  # 读取积木总数Nfirst_occurrence = {}  # 初始化哈希表,用于存储数字第一次出现的位置max_distance = -1  # 初始化最大距离为-1for i in range(N):num = int(sys.stdin.readline())  # 读取当前积木上的数字if num in first_occurrence:# 计算当前索引与第一次出现索引之间的距离distance = i - first_occurrence[num]if distance > max_distance:max_distance = distance  # 更新最大距离else:# 记录数字第一次出现的位置first_occurrence[num] = i# 输出结果print(max_distance)if __name__ == "__main__":main()

七、JavaScript算法源码

javascript">// 导入读取输入的模块
const readline = require('readline');function main() {const rl = readline.createInterface({input: process.stdin,output: process.stdout});let input = [];rl.on('line', (line) => {input.push(line);});rl.on('close', () => {let N = parseInt(input[0]); // 读取积木总数Nlet firstOccurrence = new Map(); // 初始化哈希表let maxDistance = -1; // 初始化最大距离为-1for (let i = 0; i < N; i++) {let num = BigInt(input[i + 1]); // 读取当前积木上的数字,使用BigInt处理大数if (firstOccurrence.has(num)) {// 计算当前索引与第一次出现索引之间的距离let distance = i - firstOccurrence.get(num);if (distance > maxDistance) {maxDistance = distance; // 更新最大距离}} else {// 记录数字第一次出现的位置firstOccurrence.set(num, i);}}// 输出结果console.log(maxDistance);});
}main();

八、C算法源码

#include <stdio.h>
#include <stdlib.h>// 定义哈希表的大小
#define HASH_SIZE 100003// 定义哈希表节点结构
typedef struct Node {long long key; // 数字int value; // 第一次出现的位置struct Node* next; // 指向下一个节点的指针
} Node;// 哈希函数
int hash_func(long long key) {return key % HASH_SIZE;
}int main(){int N;scanf("%d", &N); // 读取积木总数N// 初始化哈希表Node* hash_table[HASH_SIZE];for(int i=0;i<HASH_SIZE;i++) {hash_table[i] = NULL;}int maxDistance = -1; // 初始化最大距离为-1for(int i=0; i<N; i++) {long long num;scanf("%lld", &num); // 读取当前积木上的数字int hash_index = hash_func(num); // 计算哈希值Node* current = hash_table[hash_index];int found = 0;while(current != NULL){if(current->key == num){// 计算当前索引与第一次出现索引之间的距离int distance = i - current->value;if(distance > maxDistance){maxDistance = distance; // 更新最大距离}found = 1;break;}current = current->next;}if(!found){// 插入新的节点到哈希表Node* newNode = (Node*)malloc(sizeof(Node));newNode->key = num;newNode->value = i;newNode->next = hash_table[hash_index];hash_table[hash_index] = newNode;}}// 输出结果printf("%d\n", maxDistance);// 释放内存for(int i=0;i<HASH_SIZE;i++) {Node* current = hash_table[i];while(current != NULL){Node* temp = current;current = current->next;free(temp);}}return 0;
}

九、C++算法源码

#include <iostream>
#include <unordered_map>
using namespace std;int main() {ios::sync_with_stdio(false); // 关闭同步,加快输入速度cin.tie(0); // 取消cin和cout的绑定int N;cin >> N; // 读取积木总数Nunordered_map<long long, int> firstOccurrence; // 初始化哈希表int maxDistance = -1; // 初始化最大距离为-1for (int i = 0; i < N; i++) {long long num;cin >> num; // 读取当前积木上的数字if (firstOccurrence.find(num) != firstOccurrence.end()) {// 计算当前索引与第一次出现索引之间的距离int distance = i - firstOccurrence[num];if (distance > maxDistance) {maxDistance = distance; // 更新最大距离}} else {// 记录数字第一次出现的位置firstOccurrence[num] = i;}}// 输出结果cout << maxDistance << "\n";return 0;
}

🏆下一篇:华为OD机试真题 - 简易内存池(Python/JS/C/C++ 2024 E卷 200分)

🏆本文收录于,华为OD机试真题(Python/JS/C/C++)

刷的越多,抽中的概率越大,私信哪吒,备注华为OD,加入华为OD刷题交流群,每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新,全天CSDN在线答疑。

在这里插入图片描述


http://www.ppmy.cn/embedded/120042.html

相关文章

【SpringCloud】01-远程调用

1. RestTemplate 注册Bean SpringBootApplication public class CartServiceApplication {public static void main(String[] args) {SpringApplication.run(CartServiceApplication.class, args);System.out.println("cart启动成功");}Beanpublic RestTemplate re…

蜘蛛爬虫的ip来自机房,用户的爬虫来自于哪里

用户的爬虫可以来自多个不同的地方&#xff0c;具体取决于用户的配置和环境。以下是一些常见的来源&#xff1a; 1. 个人计算机 本地运行&#xff1a;许多用户可能会在自己的个人电脑上运行爬虫脚本&#xff0c;直接通过本地网络连接互联网。这种情况下&#xff0c;爬虫的 IP…

内连接的两种写法

1. **使用INNER JOIN的写法**&#xff1a; SELECT *FROM table1INNER JOIN table2ON table1.id table2.table1_id; - 这是现代SQL的标准写法&#xff0c;更清晰、更易于理解。 - JOIN关键字明确表示了连接操作&#xff0c;ON子句指定了连接条件。 - 支持多种类型的连接&…

CF1619D.New Year‘s Problem

CF1619D.New Year’s Problem 贪心 因为只能取到n-1个商店&#xff0c;因此当n-1 > m时一定会有两人在同一家商店买礼物 枚举哪一家商店&#xff0c;哪两个人买礼物&#xff0c;再与最优时候(不管n-1)的最小值取小代码附注释如下 #include<bits/stdc.h>using name…

HTML元素居中

⾏内元素⽔平垂直居中 设置⽗级标签。 ⽔平居中&#xff1a; text-align: center 垂直居中&#xff1a; line-height&#xff1a;盒⼦⾼度 ⽔平垂直都居中 <!DOCTYPE html> <html> <head><style>.container {position: relative;width: 200px;height: …

SpringBoot集成阿里easyexcel(二)Excel监听以及常用工具类

EasyExcel中非常重要的AnalysisEventListener类使用&#xff0c;继承该类并重写invoke、doAfterAllAnalysed&#xff0c;必要时重写onException方法。 Listener 中方法的执行顺序 首先先执行 invokeHeadMap() 读取表头&#xff0c;每一行都读完后&#xff0c;执行 invoke()方法…

2024 Fortinet OT工业安全高峰论坛成功举办

9月10日&#xff0c;“2024年Fortinet OT工业安全高峰论坛”于广州圆满闭幕。盛会紧扣“工业安全新行动&#xff0c;智驭AI新时代”主题&#xff0c;汇聚全球OT领域精英、技术先锋及安全领域翘楚&#xff0c;共谋OT现代化浪潮下的安全新篇章。通过多维度视角、深层次对话、鲜活…

C++中string的使用

文章目录 string类对象的常见构造string类对象的容量操作size() / length()&#xff1a;返回字符串的长度&#xff08;字符数&#xff09;。capacity()&#xff1a;返回当前字符串分配的容量&#xff08;即在重新分配内存前可以保存的字符数&#xff09;。检查是否为空&#xf…