分隔并征服算法以计数数组中元素的出现而不对其进行排序

发布于 2025-01-25 17:34:28 字数 125 浏览 7 评论 0原文

我和朋友正在讨论我们是否可以使用鸿沟和征服算法在不分类数组的情况下使用divide and Conlay算法出现了多少个特定元素k?

我们达到了一个封锁,如果我们使用二进制搜索,一旦找到元素一次,它就会停止。有什么想法吗?

Me and Friend were discussing if we can count how many a certain Element k appears in the array A[1....n] using Divide and Conquer algorithm without sorting the Array?

We reached a Blockade that if we use Binary search it will stop once it finds the element once. Any Ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

赤濁 2025-02-01 17:34:28

正如其中一条评论所提到的那样,二进制搜索用于在分类数组中找到一个元素,而在您的问题中似乎并非如此。

一个简单的划分和征服算法是将数组分成较小的部分并解决它们的问题。例如,如果算法的输入是和value k的数组,则可以编写一个将数组除以两个的函数,并计算每个数字的出现数量部分然后将它们添加在一起。

此功能采用值,该值是给定向量中的索引。最初,此功能使用left = 0right = in.size()

int NumberOfOccurances(const vector<int> &in, int k, 
                       int left, int right){
   // Base case when the size of the array is 1:
   if(right - left==1){
     return in[0] == k ? 1 : 0;
   } else {
     // Otherwise, break it into two subproblems.
     int mid = (left + right) / 2;
     return NumberOfOccurances(in, k, left, mid) +
            NumberOfOccurances(in, k, mid, right)
   }
}

而不是除以2,您也可以除以3,4或其他整数价值。

As one of the comments mentions, Binary search is used to find an element in a sorted array which doesn't seem to be the case in your problem.

A simple divide and conquer algorithm would be to break the array into smaller parts and solve the problem on them. For example, if the input of the algorithm is the array in and value k, you can write a function that divide the array by two and counts the number of occurrences in each section and then adds them together.

This function takes the left and right values which are indices in the given vector. Initially this function is called with left=0 and right=in.size():

int NumberOfOccurances(const vector<int> &in, int k, 
                       int left, int right){
   // Base case when the size of the array is 1:
   if(right - left==1){
     return in[0] == k ? 1 : 0;
   } else {
     // Otherwise, break it into two subproblems.
     int mid = (left + right) / 2;
     return NumberOfOccurances(in, k, left, mid) +
            NumberOfOccurances(in, k, mid, right)
   }
}

Instead of dividing by 2, you could also divide by 3, 4, or another integer value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文