js 数组添加n次相同元素_数组中两次出现相同元素之间的最大距离

js 数组添加n次相同元素

Prerequisite: Hashing data structure

先决条件: 哈希数据结构

Problem statement:

问题陈述:

Find maximum distance between two occurrences of same element in the array.

查找两次出现的相同元素在数组中的最大距离。

Example:

例:

Input array= [1, 2, 3, 1, 2, 4, 5, 6, 2, 3]
The maximum distance between any two same elements is 7. The leftmost position for key 2 is 1 and the rightmost position for key 2 is 8 and thus the distance is 7 which is maximum. For any other keys, the max distances between their positions are less than 7.

输入数组= [1、2、3、1、2、4、5、6、2、3]
两个相同元素之间的最大距离为7。键2的最左侧位置为1,键2的最右侧位置为8,因此距离为7,最大。 对于其他任何键,其位置之间的最大距离小于7。

Solution:

解:

We can solve this problem using a hash map (hash table). One thing is clear that to achieve maximum distance between two occurrences of the same element, we need to keep track of all positions for the elements (key). So, our target is to find maximum differences between positions for any unique element in the array. For example say, element A has positions 2, 7, 8, and another element B has positions 1, 10. Then the maximum distance for element A is 8-2=6, whereas maximum distance for element B is 10-1=9

我们可以使用哈希映射(哈希表)解决此问题。 一件事很清楚,要在同一元素的两次出现之间达到最大距离,我们需要跟踪元素(键)的所有位置。 因此,我们的目标是找出阵列中任何唯一元素的位置之间的最大差异。 例如,元素A具有位置2、7、8,而另一个元素B具有位置1、10。则元素A的最大距离为8-2 = 6,而元素B的最大距离为10-1 = 9

So how can we design the problem with the hash table and what will be the hash function?

那么我们如何设计哈希表的问题以及哈希函数是什么呢?

Okay, so here each element is our key and the hash table is has the size of the range of the array. So, if the range of the array is [0,15] then the hash table size would be 16.
What will be our hash function and how would we map the keys to the corresponding location in the hash table?

好的,所以这里的每个元素都是我们的键,哈希表具有数组范围的大小。 因此,如果数组的范围为[0,15],则哈希表大小将为16。
我们的哈希函数将是什么?如何将键映射到哈希表中的对应位置?

The hash function h(x)=x here but instead of storing the key itself using linear probing, we will store the positions using linear probing. But in my implementation, I have used vector to store easily instead of a linked list.

这里的哈希函数h(x)= x ,而不是使用线性探测存储密钥本身,我们将使用线性探测存储位置。 但是在我的实现中,我使用了vector而不是链表来轻松存储。

So, for example, if we have three 2s as our key, the hash table will store the three unique positions of 2 at location 2.

因此,例如,如果我们将三个2用作键,则哈希表将在位置2存储三个唯一的位置2。

So, after the hash table is created we can easily find the maximum distance between occurrences for each unique key and can finally achieve the maximum distance between two occurrences for the same element in the array.

因此,在创建哈希表之后,我们可以轻松找到每个唯一键的两次出现之间的最大距离,并最终可以为数组中的同一元素获得两次出现之间的最大距离。

So the algorithm will be,

因此算法将是

Step 1:

第1步:

Create the hash table like below:
Initially hash table is empty
For each key in input array:
Hash[key].push_back(key_position)

Step 2:

第2步:

Initially max_distance=0
For each location
If(difference(last position-first position)>max_distance)
Update max_distance as difference(last position-first position)
After this,
max_distance contains the maximum distance between 
two occurrences of same elements in the array.
max_distance = the maximum distance between 
two occurrences of same elements in the array.

Dry run with the example:

空运行示例:

Input array is = [1, 2, 3, 1, 2, 4, 5, 6, 2, 3]
So hash table size would be (6-1)+1=7
After creating the hash table as step1 we will have,
Index	Value
1	0->3
2	1->4->8
3	2->9
4	5
5	6
6	7
So max_distance = 7 for both 2(8-1) and 3(9-2)
Thus the answer is 7

C++ implementation:

C ++实现:

// C++ program to find maximum distance between 
// two occurrences of same element in array
#include <bits/stdc++.h>
using namespace std;
int maximum_distance_bw_occurences(vector<int> arr, int n)
{
//create a hash table where for each key the 
//hash function is h(arr[i])=arr[i]
//we will use stl map as hash table and 
//will keep i stored(i of arr[i])
//so say two keys arr[0] and arr[5] are mapping 
//to the same location, then the location will have value 0,5
//instead of the keys itself
map<int, vector<int> > hash;
//for each number
for (int i = 0; i < arr.size(); i++) {
hash[arr[i]].push_back(i);
}
//now to find max distance b/w two occurrences
//we need to check difference b/w first and 
//last position for each unique keys
//maxdiff=max(last-first) for each unique key
int maxdiff = 0;
for (auto it = hash.begin(); it != hash.end(); it++) {
int first = it->second[0];
int last = it->second[it->second.size() - 1];
if (last - first > maxdiff) {
maxdiff = last - first;
}
}
//so ans will be updated maxdiff
return maxdiff;
}
int main()
{
int n;
cout << "Enter number of elements\n";
cin >> n;
vector<int> arr(n, 0);
cout << "Input the array elements\n";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "Minimum number of deletion required to make all elements same is: ";
cout << maximum_distance_bw_occurences(arr, n) << endl;
return 0;
}

Output:

输出:

Enter number of elements
10
Input the array elements
1 2 3 1 2 4 5 6 2 3
Minimum number of deletion required to make all elements same is: 7

翻译自: https://www.includehelp.com/data-structure-tutorial/maximum-distance-between-two-occurrences-of-same-element-in-array.aspx

js 数组添加n次相同元素

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/546159.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

一道题决定去留:为什么synchronized无法禁止指令重排,却能保证有序性?

前几天有一位读者找我问一个问题&#xff0c;说是这道题可能影响了他接下来3年的技术成长。据说这位读者前面的很多问题会的都还可以&#xff0c;属于那种可过可不过的类型的&#xff0c;面试官出了最后一道题&#xff0c;就是回答的满意就可以给Offer&#xff0c;回答的不好就…

haskell程序设计语言

根据[urlhttp://www.haskell.org/haskellwiki/Haskell]haskell[/url]的[urlhttp://www.haskell.org/haskellwiki/Introduction]官方定义[/url]&#xff0c;haskell是polymorphically(多态&#xff09; statically typed静态类型&#xff09;, lazy&#xff08;懒计算&#xff0…

【Android开发】之Fragment与Acitvity通信

上一篇我们讲到与Fragment有关的常用函数&#xff0c;既然Fragment被称为是“小Activity”&#xff0c;现在我们来讲一下Fragment如何与Acitivity通信。如果上一篇还有不懂得&#xff0c;可以再看一下。传送门。 Fragment与Activity通信的方式如下&#xff1a; 一、通过初始化函…

next和hasnext_使用Java中的next()和hasNext()方法遍历List元素

next和hasnextGiven a List of integers and we have to traverse, print all its element using next() and hasNext() methods. 给定一个整数列表&#xff0c;我们必须遍历&#xff0c;使用next()和hasNext()方法打印其所有元素。 什么是hasNex()和next()方法&#xff1f; (…

「递归」的正确打开方式,看不懂你打我~

这是磊哥的第 189 期分享作者 | 田小齐来源 | 码农田小齐&#xff08;ID&#xff1a;NYCSDE&#xff09; 分享 | Java中文社群&#xff08;ID&#xff1a;javacn666&#xff09;前言 递归&#xff0c;是一个非常重要的概念&#xff0c;也是面试中非常喜欢考的。因为它不但能考察…

Log4cpp 使用手册

参考资料&#xff1a; log4cpp 配置 与 使用http://www.cnblogs.com/welkinwalker/archive/2011/06/23/2088197.html 便利的开发工具-log4cpp快速使用指南 http://www.ibm.com/developerworks/cn/linux/l-log4cpp/ Log4cpp配置文件格式说明 http://sogo6.iteye.com/blog/115431…

适合初学编程的一些项目

学习了一门语言以及数据结构之后&#xff0c;通常需要做一些项目来巩固所学的知识&#xff0c;我感觉最好是用写一些简单的小工具或者小游戏&#xff0c;能够提高自己的编程能力&#xff0c;也能进一步提高自己学习的兴趣。最好的是将自己想做的事情用程序的实现&#xff0c;比…

python 5的倍数_查找所有低于1000的数字的和,这是Python中3或5的倍数

python 5的倍数Sometimes, we need to find the sum of all integers or numbers that are completely divisible by 3 and 5 up to thousands, since thousands are a too large number that’s why it becomes difficult for us. So, here we will do it in Python programmi…

switch 的性能提升了 3 倍,我只用了这一招!

这是我的第 190 期分享作者 | 王磊来源 | Java中文社群&#xff08;ID&#xff1a;javacn666&#xff09; 分享 | Java中文社群&#xff08;ID&#xff1a;javacn666&#xff09;上一篇《if快还是switch快&#xff1f;解密switch背后的秘密》我们测试了 if 和 switch 的性能&am…

HashMap get不出对象时出错 解决

为什么80%的码农都做不了架构师&#xff1f;>>> 如题&#xff1a; Map map new HashMap(); map.put("1", "A"); map.put("2", "A"); map.put("3", "A"); map.put("4", "A")…

安装codeblocks和wxwidgets及opencv

codeblocks 是一款开放源代码的跨平台的c/c++集成开发环境,它是用wxwidgets 开发的,并且支持插件,功能很强大。可以用来在windows开发各种程序。下面记录一下我安装该软件的过程: 首先到http://www.codeblocks.org/downloads 下载该软件,选择含mingw的文件(codeblocks-10…

Java LinkedList boolean addAll(int index,Collection c)方法,带有示例

LinkedList boolean addAll(int index&#xff0c;Collection c)方法 (LinkedList boolean addAll(int index, Collection c) method) This method is available in package java.util.Collection and here, Collection is an interface. 该方法在java.util.Collection包中可用…

高质量SQL的30条建议!(后端必备)

这是我的第 191 期分享作者 | 捡田螺的小男孩来源 | 捡田螺的小男孩&#xff08;ID&#xff1a;gh_873ad5979a0b&#xff09; 分享 | Java中文社群&#xff08;ID&#xff1a;javacn666&#xff09;本文将结合实例demo&#xff0c;阐述30条有关于优化SQL的建议&#xff0c;多数…

滤波电容的选择(调试中)

整个系统高电平时12V&#xff0c;信号是ms级的负脉冲&#xff0c;脉冲的下降沿很陡&#xff0c;当用示波器展开看的时候&#xff0c;发现了低于0V的过冲&#xff0c;能低到-6V&#xff08;相当严重&#xff09;&#xff0c;这是在整个箱子的出口处测量到的。在主控板&#xff0…

sicp

sicp (structure and interpretion of computer programs &#xff0c;编号为6.001 )是麻省理工学院的一门经典计算机入门课程&#xff0c;虽然近年被另外一门课程所取代&#xff08;6.00 或6.01 &#xff09;&#xff0c;但最近好像有复活 的迹象。Perter Norvig 写了关于sicp…

Redis的自白:我为什么在单线程的这条路上越走越远?

这是我的第 192 期分享作者 | 王磊来源 | Java中文社群&#xff08;ID&#xff1a;javacn666&#xff09;转载请联系授权&#xff08;微信ID&#xff1a;GG_Stone&#xff09;我是 Redis&#xff0c;今年 11 岁了~曾几何时我是辣么的单纯&#xff0c;辣么的可爱&#xff0c;而如…

两个矩阵相乘的乘法次数_C ++程序将两个数字相乘而不使用乘法运算符

两个矩阵相乘的乘法次数The problem is we have two integer numbers and find the multiplication of them without using the multiplication operator. This problem can be solved using the Russian peasant algorithm. Assume the two given numbers are m and n. Initia…

关于引用

2019独角兽企业重金招聘Python工程师标准>>> 1、 <!-- lang: html --> <!DOCTYPE HTML> <!-- lang: html --> <html> <!-- lang: html --> <head> <!-- lang: html --> <meta charset"utf-8" /> <!--…

ruby array_在Ruby中使用Array.delete()和Array.delete_at()从Array中移除元素

ruby arrayRuby Array.delete()和Array.delete_at()方法 (Ruby Array.delete() and Array.delete_at() methods) In the last article, we have seen how we can remove the elements from an instance of Array class with the help of Array.pop() and Array.shift()? 在上一…

一口气说出 6 种延时队列的实现方法,面试官满意的笑了

这是我的第 193 期分享作者 | 程序员内点事来源 | 程序员内点事&#xff08;ID&#xff1a;chegnxy-nds&#xff09; 分享 | Java中文社群&#xff08;ID&#xff1a;javacn666&#xff09;五一期间原计划是写两篇文章&#xff0c;看一本技术类书籍&#xff0c;结果这五天由于自…