Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从int[]删除重复项_Java - Fatal编程技术网

Java 从int[]删除重复项

Java 从int[]删除重复项,java,Java,刚接触Java,正在尝试使用kata。我们的目标是编写一个函数,从int[]中删除重复值,并返回一个int[],其中删除了重复值,并且返回的顺序与最初相同 我已经被困了一段时间了,有人能帮我指出正确的方向吗?目前的进展: import java.util.*; public class UniqueArray { public static int[] unique(int[] integers) { // Return integers when duplicates are n

刚接触Java,正在尝试使用kata。我们的目标是编写一个函数,从int[]中删除重复值,并返回一个int[],其中删除了重复值,并且返回的顺序与最初相同

我已经被困了一段时间了,有人能帮我指出正确的方向吗?目前的进展:

import java.util.*;

public class UniqueArray {
  public static int[] unique(int[] integers) {
    // Return integers when duplicates are not possible
    if (integers.length <= 1) {
      return integers;
    }

    ArrayList<Integer> newArray = new ArrayList<Integer>();

    // Check each word in integers against the new array
    for (int i = 0, j = integers.length; i < j; i++) {
      for (int k = 0, l = newArray.size(); k < l; k++) {

        // If match found, move to next int from integers
        if (integers[i] == newArray.get(k).intValue()) {
          break;
        }

      // If no matches found, add to new array
      newArray.add(integers[k]);
      }
    }

    // Convert ArrayList to int[]
    int[] finalArray = new int[newArray.size()];
    for (int i = 0, s = newArray.size(); i < s; i++) {
      finalArray[i] = newArray.get(i).intValue();
    }

    return finalArray;
  }
}
import java.util.*;
公共类唯一数组{
公共静态int[]唯一(int[]整数){
//不可能重复时返回整数

如果(integers.length数组列表
为空,则不会执行内部循环

您可以遵循以下逻辑:

  • 在整数数组上循环。
    • 检查ArrayList是否已包含整数。如果未包含,请添加它

您只添加到newArray循环中的
newArray
,第一次执行0次,之后每次执行0次,因为这是您添加到它的唯一位置。了解程序流程。调试。(并修复缩进,以提高可读性)我的函数返回一个长度为0的数组,我不确定是哪个部分失败了,是单词添加到newArray的部分,还是newArray转换为finalArray的部分。我已经学了这么多个小时了,我的大脑都在融化,但我不想回避这个问题。很好,你没有给出代码,而是给出文本ally解释一下!我怎么没注意到?太棒了,正是我想要的答案。谢谢!