二分查找之天平称重,称出最重的小球
2015-01-16 21:37
302 查看
题目:有n个小球,其中有一个比其他的都要重,已知有一个天平,怎么用最少的次数把小球找出来?
个人代码如下:
输出:
个人小结:
以上的方法是用了二分查找的方式。思路是:
1)如果剩余的总数是奇数的话,平均分成两半,那么就有一个多出来,
如果这两半的数量相等,那么多出来那个一定是那个重的小球。如果不相等,找出重的那边继续切成两半进行递归。
2)如果剩余的总数是偶数的话,就可以平均的分成两半。找出重的那边继续切分,依此不断递归,直到找到那个重的小球,或者重的小球不存在。
3)如果重的小球不存在,那么返回-1。
个人代码如下:
#include <iostream> #include <numeric> using namespace std; int GetAbnormalBall(int a[], int begin, int end, int &count) { if(begin == end) return a[begin]; int Num = (end - begin) + 1; int HalfNum = Num / 2; ++count; int fweight = accumulate(a + begin, a + begin + HalfNum, 0); int bweight = accumulate(a + begin + HalfNum, a + begin + 2 * HalfNum, 0); if(Num % 2 != 0) //剩余数量是奇数的时候 { if(fweight == bweight) return a[end]; else if(fweight > bweight) return GetAbnormalBall(a, begin, begin + HalfNum - 1, count); else return GetAbnormalBall(a, begin + HalfNum, end, count); } else if(fweight > bweight) //剩余数量是偶数的时候 return GetAbnormalBall(a, begin, begin + HalfNum - 1, count); else if(fweight < bweight) return GetAbnormalBall(a, begin + HalfNum, end, count); else return -1; //表示不存在 } int main() { //int a[] = {4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; int count = 0; int a[] = {1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1}; int len = sizeof(a)/sizeof(int); cout<< GetAbnormalBall(a, 0, len - 1, count) <<endl; cout<< "查找的次数: " << count <<endl; }
输出:
个人小结:
以上的方法是用了二分查找的方式。思路是:
1)如果剩余的总数是奇数的话,平均分成两半,那么就有一个多出来,
如果这两半的数量相等,那么多出来那个一定是那个重的小球。如果不相等,找出重的那边继续切成两半进行递归。
2)如果剩余的总数是偶数的话,就可以平均的分成两半。找出重的那边继续切分,依此不断递归,直到找到那个重的小球,或者重的小球不存在。
3)如果重的小球不存在,那么返回-1。
相关文章推荐
- 【Java实践】十二小球天平三次称重问题
- 32. 百度面试题:用天平(只能比较,不能称重)从一堆小球中找出其中唯一一个较轻的,使用x次天平,最多可以从y个小球中找出较轻的那个,求y与x的关系式
- 个人小项目:现有12个小球和一个天平,小球中有一个重量与其它的不同,称重几次能将这个小球找出来
- 用天平(只能比较,不能称重)从一堆小球中找出其中唯一一个较轻的,使用x 次天平, 最多可以从y 个小球中找出较轻的那个,求y 与x 的关系式。
- 用天平(只能比较,不能称重)从一堆小球中找出其中唯一一个较轻的,使用x次天平,
- 二分查找
- 不光是查找值!"二分搜索"总结
- C语言 数据结构之排序与查找 数据结构实验之查找四:二分查找
- TimesIsMoney(二分查找)
- 重学java之随机数组二分查找
- 二分查找模板
- 二分查找
- 【leetcode】有重复的旋转排序数组查找(二分)
- 分治法--二分查找、乘方、斐波那契数
- Java实现二分查找
- Search a 2D Matrix:二分查找二维数组
- 如何对日志文件进行二分查找?开源文件二分查找工具『timecat』介绍
- Java数据结构和算法总结-数组、二分查找
- 二分查找代码
- Python实现二分查找