您的位置:首页 > 职场人生

Careercup - Google面试题 - 6407924087783424

2014-05-07 15:27 309 查看
2014-05-07 15:17

题目链接

原题:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: