【问题标题】:How to get get rid of duplicate values in an int array?如何摆脱 int 数组中的重复值?
【发布时间】:2015-05-03 13:12:25
【问题描述】:

问题正如标题所说,如何去除整数数组中的重复值?我想要它,所以用户输入五个数字,所有数字都在 10 到 100 之间。关键是我必须拥有它,这样如果他们输入的值已经输入到数组中,它就不会计数。这是我到目前为止的代码:

public static void main(String[]args){
    Scanner input = new Scanner(System.in);

    int[] intArray = new int[5]; //max of 5 values

    for(int i = 0; i < 5; i++){
        System.out.println("Please enter your desired number that is between 10 and 100: ");
            intArray[i] = input.nextInt(); //puts the value into the array
        }
    System.out.println(Arrays.toString(intArray)); //for test purposes to make sure the array was correctly taking in the values
    }
}


    System.out.println(Arrays.toString(intArray)); //for test purposes to make sure the array was correctly taking in the values

我对如何制作它感到困惑,所以如果用户输入数组中已经存在的数字,它就不会添加它。这是我的意思的一个例子,假设用户输入数字 15、22、46、46、77,一旦程序完成循环五次,它将打印出以下内容:[15、22、46、77]。我被困在如何做到这一点上。此外,我还编辑了 if 数字在 10 到 100 之间的 if 语句,以便于阅读,并进入手头的要点。

【问题讨论】:

    标签: java arrays int duplicates duplicate-removal


    【解决方案1】:

    使用 Set 怎么样?特别是 LinkedHashSet 允许您在 O(n) 时间和内存中执行此操作,同时保留输入的顺序。在你说“但我不能使用 HashSet”之前,你需要它的行为以获得最佳解决方案,所以后续问题可能是“我将如何实现 LinkedHashSet,可能将逻辑烘焙到我的程序中?”

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
    
        Set<Integer> intSet = new LinkedHashSet<>();
        int[] intArray = new int[5]; //max of 5 values
    
        for (int i = 0; i < 5; i++) {
            System.out.println("Please enter your desired number that is between 10 and 100: ");
            intSet.add(input.nextInt());
        }
    
        int[] intArray = new int[intSet.size()];
    
        int i = 0;
        for (Integer val : intSet) {
            intArray[i++] = val;
        }
    }
    

    【讨论】:

      【解决方案2】:

      你是说你想要一个可变数量的数字,所以在这里数组不是正确的选择,请改用 ArrayList。

      类似:

      List<Integer> intList = new ArrayList<Integer>();
      int maxElements = 5; //Set max value here
      for(int i = 0; i < maxElements ; i++)
      {
          System.out.println("Please enter your desired number that is between 10 and 100: ");
          Integer newNumber = input.nextInt();
          if(newNumber  >= 10 && newNumber  <= 100)
          {
              Boolean found = false;
              foreach (Integer check : intList)
              {
                  if (check == newNumber)
                  {
                       found = true;
                       break;
                  }
              }
              if (!found) intList.Add(newNumber);
          }
          else if(newNumber < 10 || newNumber > 100)
          {
              System.out.println("Enter a valid number next time, this number will not be counted in the results.");
          }
      }
      

      重复检查:我添加的那个内部循环检查是否有另一个具有相同值的元素,在这种情况下会跳过你所说的数字。

      我在没有电脑的情况下写了这篇文章,所以我可以把一些东西混在一起,但你明白了。

      【讨论】:

      • 这将花费O(n^2) 时间。
      • 我知道,但元素数量如此之少,我认为它不会那么重要。
      【解决方案3】:

      如果您只需要从用户输入的数字中选择唯一的数字,请不要一开始就将它们存储在数组中。

      相反,将它们存储在 HashMap/Hashtable 中,然后在用户输入完成后将其转换为数组。

      另一种方法是使用集合集合。将收到的每个数字添加到 Set 的实例中,最后将 Set 转换为 Array。 Set 默认保持唯一性。

      public static void main(String[]args){
          Scanner input = new Scanner(System.in);
          int[] intArray = new int[5]; //max of 5 values
          Set<Integer> uniques = new HashSet<Integer>();
          for(int i = 0; i < 5; i++){
              System.out.println("Please enter your desired number that is between 10 and 100: ");
              uniques.add(input.nextInt()); //puts the value in the set
          }
          System.out.println(Arrays.toString(uniques.toArray())); //for test purposes to make sure the array was correctly taking in the values
      }
      

      【讨论】:

      • 我该怎么做?我以前从未处理过 HashMap 或 Hashtable。
      • 同意为此使用Set -- HashMapHashtable 不合适。
      • Well Sets 内部与 HashMap 或 Hashtable 没有太大区别。可以适应这种用途。
      • 我明白这一点,但是当一个简单的Set 基本上是为此目的而制作时,没有理由使用键 -> 值数据结构来解决这个问题。
      • 来自 HashSet 文档:This class implements the Set interface, backed by a hash table (actually a HashMap instance).
      【解决方案4】:

      一个班轮就能完成你想要的:

      Set<Integer> noDuplicates = new LinkedHashSet<>(Arrays.asList(intArray));
      

      在您读取值并将它们存储在您的intArray 中之后执行此操作。

      如果要保留输入值的顺序,请使用LinkedHashSet,否则仅使用HashSet

      Set 是一个不能有重复的集合。

      【讨论】:

        【解决方案5】:
        1. 使您的数组大小为 100 并使用输入作为索引。在更新数组[输入] = 输入之前,检查数组的索引(输入编号)的值。

        2. 使用映射存储输入值作为键。在将值保存到数组之前,请检查键是否在地图中。

        【讨论】:

        • 对于您的第一个“解决方案”,如果我输入0 会怎样? array[0] == 0 默认情况下,因此您的逻辑会声称我已经输入了该值。 “更好”的解决方案是一个布尔数组,当我输入 idx 时将其设置为 array[idx]true
        • @ColeJohnson 我没有提到初始化数组。在这种情况下。数组应该用负数初始化。但是,如果我们只检查正数( 10 ~ 100 ),我们不关心 0 或负输入值。
        猜你喜欢
        • 1970-01-01
        • 2020-07-30
        • 1970-01-01
        • 2017-01-19
        • 1970-01-01
        • 2014-09-25
        • 1970-01-01
        • 2019-04-21
        • 1970-01-01
        相关资源
        最近更新 更多