gpt4 book ai didi

java - 从 val : Can't import anything other than java. util.Arrays 返回最远的 K

转载 作者:太空宇宙 更新时间:2023-11-04 07:25:33 25 4
gpt4 key购买 nike

需要返回k个元素a[i],使得ABS(a[i] - val)是第k个最大的评估。我的代码仅适用于大于 val 的整数。如果整数小于 val,它将失败。我可以在不导入 java.util.Arrays 以外的任何内容的情况下执行此操作吗?任何帮助将不胜感激!

import java.util.Arrays;

public final class Selector {

private Selector() {
}
public static int[] farthestK(int[] a, int val, int k) {// This line should not change
int[] b = new int[a.length];
for (int i = 0; i < b.length; i++) {
b[i] = Math.abs(a[i] - val);
}
Arrays.sort(b);
int[] c = new int[k];
int w = 0;
for (int i = b.length-1; i > b.length-k-1; i--) {
c[w] = b[i] + val;
w++;
}
return c;
}

测试用例:

import org.junit.Assert;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;


public class SelectorTest {


/** Fixture initialization (common initialization
* for all tests). **/
@Before public void setUp() {
}
@Test public void farthestKTest() {
int[] a = {-2, 4, -6, 7, 8, 13, 15};
int[] expected = {15, -6, 13, -2};
int[] actual = Selector.farthestK(a, 4, 4);
Assert.assertArrayEquals(expected, actual);
}
}

There was 1 failure:
1) farthestKTest(SelectorTest)
arrays first differed at element [1]; expected:<-6> but was:<13>
FAILURES!!!
Tests run: 1, Failures: 1

最佳答案

通过将距离存储为绝对值,您将破坏最后一个 for 循环,该循环根据绝对值重新计算原始值。

使用一个比较器,它使用abs值进行比较,但将数组值与搜索值的差值存储在数组b中怎么样?

这里会是这样的:

public static int[] farthestK(int[] a, int val, int k) {// This line should not change
Integer[] b = new Integer[a.length];
for (int i = 0; i < b.length; i++) {
b[i] = a[i] - val;
}
Arrays.sort(b, new Comparator<Integer>() {

@Override
public int compare(Integer arg0, Integer arg1) {
return Integer.valueOf(Math.abs(arg0)).compareTo(Math.abs(arg1));
}
});
int[] c = new int[k];
int w = 0;
for (int i = b.length - 1; i > b.length - k - 1; i--) {
c[w] = b[i] + val;
w++;
}
return c;
}

关于java - 从 val : Can't import anything other than java. util.Arrays 返回最远的 K,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18606318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com