[英]how to filter an array using a binary representation of an integer argument?
n: 88 = 23 + 24 + 26 (1011000) array: 8, 4, 9, 0, 3, 1, 2 indexes: 0 1 2 3 4 5 6 selected * * * result 0, 3, 2 so the result of filtering {8, 4, 9, 0, 3, 1, 2} using 88 would be {0, 3, 2} In the
上面,选择的元素是那些索引用作 88 的二进制表示中的指数的元素。 换句话说,结果选择了 a[3]、a[4] 和 a[6],因为 3、4和 6 是总和为 88 的 2 的幂。编写一个名为 filterArray 的方法,它接受一个数组和一个非负整数,并返回使用整数的二进制表示过滤数组的结果。 返回的数组必须足够大以包含过滤的元素并且不能更大。 所以在上面的例子中,返回的数组的长度是 3,而不是 7(这是原始数组的大小)。此外,如果输入数组不够大,无法包含所有选定的元素,则该方法返回 null。 例如,如果 n=3 用于过滤数组 a = {18},则该方法应返回 null,因为 3=20+21 并且因此要求数组至少具有 2 个元素 a[0] 和 a 1 ,但是没有1 。 如果你使用 Java 或 C#,函数的签名是 int[ ] filterArray(int[ ] a, int n)
我有这个问题我想解决,我写了这段代码
public static int[] filterArray(int[] a, int n) {
int[] x = new int[a.length];
int j = 0;
int count = 0;
while (n > 0) {
int digit = n % 2;
n /= 2;
x[j] = digit;
j++;
}
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(x));
for (int k = 0; k < x.length; k++) {
if (x[k] == 1)
count++;
}
System.out.println("count is " + count);
int[] z = new int[count];
for (int i = 0; i < z.length; i++) {
for (int k = 0; k < x.length; k++) {
if(x[k] == 1) {
z[i] = a[k];
}
}
}
System.out.println(Arrays.toString(z));
return x;
}
当我尝试使用测试数组进行测试时
System.out.println(Arrays.toString(filterArray(new int[] { 0, 9, 12, 18, -6 }, 11)));
它给了我以下输出
[18, 18, 18]
正确的输出是
[0, 9, 18]
问题在于您的嵌套循环:您正在为输出数组的每个元素迭代整个输入数组,并继续用最后找到的元素覆盖值(使用调试器逐步执行您的代码,您会看到)。
要解决这个问题,请交换循环并跟踪“下一个”输出索引:
int i = 0;
for (int k = 0; k < x.length; k++) {
if(x[k] == 1) {
z[i] = a[k];
i++; //advance the output index
}
}
这也将使您的代码更快,因为现在您没有 O(n 2 ) 复杂度,而只有 O(n)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.