Careercup - Google面试题 - 6407924087783424
2014-05-07 15:27
309 查看
2014-05-07 15:17
题目链接
原题:
题目:给定一个长度为n的整数数组。每次允许你选取其中两个元素,对一个+1,对另一个-1。如果允许你执行任意多次这样的操作,问你至多能把多少个元素变成同一个数?
解法:第一次看这个题目还看不到懂,但想通了以后发现就是解题几乎就是一句话的事情。每次进行这样的操作时,所有元素加起来的总和一直保持不变,所以只要看看总和能否被n整除。如果能整除,则n个数都会变成一样。否则,只能得到n - 1个一样的数,剩下一个不一样。最后,注意取模运算对于负数的处理。
代码:
题目链接
原题:
Given an array of n elements (a1,a2,..ai,...,an). You are allow to chose any index i and j, such that (i!=j) and allow to perform increment operation on ai = ai+1 and decrements operation on aj = aj - 1 infinite number of times. How many maximum number of elements you can find that have same number.
题目:给定一个长度为n的整数数组。每次允许你选取其中两个元素,对一个+1,对另一个-1。如果允许你执行任意多次这样的操作,问你至多能把多少个元素变成同一个数?
解法:第一次看这个题目还看不到懂,但想通了以后发现就是解题几乎就是一句话的事情。每次进行这样的操作时,所有元素加起来的总和一直保持不变,所以只要看看总和能否被n整除。如果能整除,则n个数都会变成一样。否则,只能得到n - 1个一样的数,剩下一个不一样。最后,注意取模运算对于负数的处理。
代码:
// http://www.careercup.com/question?id=6407924087783424 #include <iostream> #include <vector> using namespace std; inline int mod(int x, int y) { return x % y >= 0 ? x % y : y - (y - x) % y; } int main() { vector<int> v; int n; int i; int sum; while (cin >> n && n > 0) { v.resize(n); for (i = 0; i < n; ++i) { cin >> v[i]; } sum = 0; for (i = 0; i < n; ++i) { sum = mod(sum + v[i], n); } cout << (sum ? n - 1 : n) << endl; v.clear(); } return 0; }
相关文章推荐
- Careercup - Google面试题 - 5732809947742208
- Careercup - Google面试题 - 5735304249999360
- Careercup - Google面试题 - 5898529851572224
- Careercup - Google面试题 - 5692127791022080
- Careercup - Google面试题 - 5205167846719488
- Careercup - Google面试题 - 6331648220069888
- Careercup - Google面试题 - 4857362737266688
- Careercup - Google面试题 - 5377673471721472
- Careercup - Google面试题 - 5424071030341632
- Careercup - Google面试题 - 5680330589601792
- Careercup - Google面试题 - 4877486110277632
- Careercup - Google面试题 - 5085331422445568
- Careercup - Google面试题 - 4716965625069568
- Careercup - Google面试题 - 5162732873580544
- Careercup - Google面试题 - 4807591515389952
- Careercup - Google面试题 - 6283958983589888
- Careercup - Google面试题 - 5661939564806144
- Careercup - Google面试题 - 6271724635029504
- Careercup - Google面试题 - 6253551042953216
- Careercup - Google面试题 - 4699414551592960