【发布时间】:2016-08-24 11:57:39
【问题描述】:
方向:
给定一个int[] x 和一个百分比p (0 - 100),找到x 中最小的元素y,使得x 的至少百分比p 元素小于或等于y。
Example 1:
x = {-3, -5, 2, 1}, p = 50
Method should return -3
Reason: 50% of the elements in x are less than or equal to -3: -5 and -3
Example 2:
x = {7, 9, 2, -10, -6}, p = 50
Method should return 2
Reason: 60 percent of the elements in x are less than or equal to 2: 2, -10 and -6
-6 would be wrong because only 40% of the elements are less than or equal
(100% of the elements are less than or equal to 9, but that isn't the smallest value)
Example 3:
x = {1,2,3,4,5,6,7,8,9,1,2,3,4,5,7,9,5,43,124,94}, p = 0
Method should return 1
Reason: Only 0% is needed, so in theory any number will do, but 1 is the smallest value
到目前为止,这是我为该方法编写的内容:
public static int fractile(int[] x, int p)
{
int smallestInt = x[0];
for (int i = 0; i < x.length; i++) {
int testNum = x[i];
int percentage;
int count = 0;
for (int j = 0; j < x.length; j++) {
if (x[j] <= testNum)
count++;
}
percentage = (count / x.length) * 100;
if (testNum <= smallestInt && percentage >= p)
smallestInt = testNum;
}
return smallestInt;
}
但我的样本编号输出错误:
INPUT:
[6, 5, 4, 8, 3, 2]
40%
Method returns: 6
INPUT:
[7, 5, 6, 4, 3, 8, 7, 6, 9, 10]
20%
Method returns: 7
INPUT:
[3, 4, 2, 6, 7, 5, 4, 4, 3, 2]
60%
Method returns: 3
这几乎就好像它正在抓取第一个索引并且不查看它后面的数字,但我不知道为什么。
我做错了什么?
【问题讨论】:
-
最大的问题可能是你的初始化行
int smallestInt = x[0];。这是完全错误的。将其替换为int smallestInt = Integer.MAX_VALUE -
罗伯特,你是指最高指数还是最高价值?
-
请记住,您必须按照下面的一些 cmets 和答案中的说明修正百分比计算。