您认为哪种解决方案最有效?怎么说呢? [英] Which solution do you think is the most efficient? And how to tell it?

查看:76
本文介绍了您认为哪种解决方案最有效?怎么说呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

网站上提供的代码。

最小的元素重复'k'次(不限于小范围) - GeeksforGeeks [ ^ ]

这两个中最有效的代码是什么?

顺便说一下,两者都显示正确的输出。



我尝试了什么:



The code given in the website.
Smallest element repeated exactly ‘k’ times (not limited to small range) - GeeksforGeeks[^]
Which is the most efficient code out of these two?
Btw, both shows the correct output.

What I have tried:

/*https://www.geeksforgeeks.org/smallest-element-repeated-exactly-k-times-not-limited-small-range/
Smallest element repeated exactly ‘k’ times (not limited to small range)
*/
#include<bits/stdc++.h>
using namespace std;
int no_of_chars = 10;
int smallrepeat(int s[],int k, int n)
{
	int hash[no_of_chars] = {0};
	//Storing the frequency of occurances.
	for(int i=0;i<n;i++)
		hash[s[i]]++;
	//Finding smallest element repeated exactly 'k' times
	int repeatmore = 9;
	for(int i=0;i<n;i++){
		if(hash[s[i]] && (hash[s[i]] == k) && (s[i] < repeatmore))
			repeatmore = s[i];
	}

	return repeatmore;

}
int main()
{
	int s[] = { 2, 2, 1, 3, 1 };
	int n = sizeof(s)/sizeof(s[0]);
	int k = 2;
	cout<<"Smallest element repeated exactly ‘k’ times :"<<smallrepeat(s,k,n)<<endl;
}

推荐答案

网站版本可能是两者中较快的,但只是非常非常小的边际因为它在循环中只有一个较少的比较。您的附加检查哈希数组的零值似乎是不必要的。没有那个检查,两者将具有几乎相同的性能。除非您使用非常大的数据阵列并测试多个循环,例如100K或更多,否则差异可能是无法测量的。



在发布模式下,代码中的细微差别将大部分由编译器优化。那些将是for循环的.begin()和.end()部分以及通常内联的对min的调用。
The website version is likely to be the faster of the two but only by a very, very small margin because it has one less comparison within its loop. Yours has an additional check for a zero value of the hash array which seems unnecessary. Without that check the two would have nearly identical performance. The difference would probably be unmeasurable unless you use a very large data array and test multiple loops, like 100K or more.

In release mode, the subtle differences in the code will be mostly optimized away by the compiler. Those would be the .begin() and .end() parts of the for loop and the call to min which is usually inlined.


它们基本相同。请注意,如果找不到该元素,您的程序将不会生成与Web侧相同的输出。
They are basically the same. Note your program doesn't produce the same output of the one on the webside if the element is not found.


这篇关于您认为哪种解决方案最有效?怎么说呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆