【问题标题】:A method for counting unique elements in a array with loop (Java)一种使用循环计算数组中唯一元素的方法(Java)
【发布时间】:2021-07-15 18:22:41
【问题描述】:

我正在尝试创建一种方法来计算数组中唯一元素的数量。例如,如果数组包含 [1,2,3,4,5,1,5],则有 3 个唯一元素,我的方法应该返回数字 3。

这是我目前得到的:

static int numberOfUniqueIntegers(int[] number, int len) {
    int unique = 0;
    for (int i = 0; i < len; i++){
        int j;
        for (j = 0; j < i; j ++) {
            if (number[i] == number[j]) {
                break;
            }
        }
        if (i == j);
        unique++;
    }

    return unique;

}

该方法接受数组number和一个整数len(即数组的长度)。

但在这种情况下:[1,2,3,4,5,1,5] 我的方法将返回 5,而不是 3。我需要检查该数字是否以前重复过,如果没有 独一无二的++。

【问题讨论】:

  • 在计数前对复制数组中的数字进行排序
  • Java 有一个 Set 集合。这将非常适合您的用例。
  • @Moritz Makowsi 的回答将是最好的起点。最好使用调试器或输出一些日志来弄清楚你的代码在做什么。
  • 您的问题不清楚。 [1, 2, 3, 4, 5, 1, 5] 中有 5 个独特的元素:[1, 2, 3, 4, 5]。怎么只有3个?什么意思?
  • @JonZarate 有 3 个元素只出现一次。

标签: java arrays unique


【解决方案1】:

您可以创建一个频率Map,然后获取仅出现一次的键的数量。

static int numberOfUniqueIntegers(int[] number) {
    Map<Integer, Long> freq = Arrays.stream(number).boxed().collect(
       Collectors.groupingBy(x -> x, Collectors.counting()));
    return (int) freq.entrySet().stream().filter(e -> e.getValue().equals(1L))
        .map(Map.Entry::getKey).count();
}

Demo

【讨论】:

    【解决方案2】:

    这个应该可以,只需将已经看到的元素保留在一个单独的数组中:

    static int numberOfUniqueIntegers(int[] number, int len) {
        int unique = 0;
        List<Integer> temp = new ArrayList<>();
        for (int i = 0; i < len; i++){
            if (!temp.contains(number[i]))
            {
                unique ++;
                temp.add(number[i]);
            }
        }
    
        return unique;
    
    }
    

    【讨论】:

    • 这不会编译并且会返回0
    • 是的,抱歉,我录制的太快了,错过了“!”。但我认为你的解决方案更好,更先进。
    【解决方案3】:
    static int numberOfUniqueIntegers(int[] number, int len) {
        int unique = 0;
        boolean isRepeated;
        for (int i = 0; i < len; i++){
          isRepeated = false;//setting to defalut value
            int j;
            for (j = 0; j < len; j ++) {
              if(j == i) continue;
                if (number[i] == number[j]) {
                  isRepeated = true;//if caught duplicate
                    break;
                }
            }
            //if not caught duplicate then increment unique ++
            if(!isRepeated) unique++;
        }
    
        return unique;
    
    }
    

    出了什么问题?
    You have to match every value with everyother value which you did not as because you are just using an array and there is no way to figure if futures values had a match in past. So, you have to cover the length of array and check each value against every value in it. if it was to be written using java collections then it be would much simpler and with less time complexity

    【讨论】:

    • 感谢您的反馈和代码!我喜欢这种构建代码(尽管我知道它可能不是最有效的)。
    【解决方案4】:

    如果您需要在不使用任何额外空间的情况下执行此操作,例如Set,那么您别无选择,只能将数组中的每个元素与所有其他元素进行比较,O(n^2) 解决方案。

    static int numberOfUniqueIntegers(int[] number, int len)
    {
        int unique = 0;
    
        for (int i = 0; i < len; i++)
        {
            int j = 0;
            for (; j < len; j++)
                if (i != j && number[i] == number[j]) break;
            if (j == len) unique++;
        }
    
        return unique;
    
    }
    

    如果您可以使用额外的空间,那么options 使用Set

    【讨论】:

    • 谢谢!!这正是我要找的!
    【解决方案5】:

    您可以尝试 O(2n) 复杂度

    static int numberOfUniqueIntegers() {
        //int[] abc = { 1, 2, 3, 4, 5, 1, 5 };
    
        int[] abc = { 1, 1, 1 };
    
        Map<Integer, Integer> st = new HashMap();
        int unique = 0;
        for (int i = 0; i < abc.length; i++) {
            if (st.isEmpty() || st.containsKey(abc[i])) {
                Integer vl = st.get(abc[i]);
                st.put(abc[i], Objects.nonNull(vl) ? (vl + 1) : 1);
            } else {
                st.put(abc[i], 1);
            }
    
        }
        for (int i : st.keySet()) {
            if (st.get(i) == 1) {
                unique = unique + 1;
            }
        }
        System.out.println(st);
        return unique;
    }
    

    【讨论】:

      【解决方案6】:

      最简单的方法就是使用Set

      int[] s = { 1, 2, 1, 5, 3, 4, 5, 1, 1, 5 };
      int count = numberOfUniqueIntegers(s);
      System.out.println("Count = " + count);
      

      打印

      Count = 3
      
      • Set#add 如果元素存在则返回false,否则返回true
      • 如果seen 不包含它,请添加到unique
      • 如果已经看到,请从unique 中删除。
      • 只会保留唯一的。
      static int numberOfUniqueIntegers(int[] number) {
          Set<Integer> seen = new HashSet<>();
          Set<Integer> unique = new HashSet<>();
          for (int i : number) {
              if (!seen.add(i)) {
                  unique.remove(i);
                  continue;
              }
              unique.add(i);
          }
          return unique.size();
      }
      
      

      由于Set 的性质,上述在O(n) 中有效,不需要对元素进行显式计数。

      【讨论】:

        【解决方案7】:

        通常问这样的问题,很多堆栈溢出的答案会给你解决方案,但是,这可能不利于你自己解决问题。

        请记住,有多种方法可以解决此类问题。

        • 使用Set(一种专门处理uniques的数据结构)
        • 排序和计数。在重复时,继续。

        只是想指出您的代码存在的潜在问题。您在条件子句上使用了终止符if(i == j);

        您的代码将正确编译和运行,但它只会检查比较并每次运行count++。你会想要修复这个子句。

        正确的语法应该是

        if (i == j) {
           count++
        } 
        

        检查评论的确切行:

        static int numberOfUniqueIntegers(int[] number, int len) {
            int unique = 0;
             for (int i = 0; i < len; i++){
                int j;
                for (j = 0; j < i; j ++) {
                    if (number[i] == number[j]) {
                        break;
                    }
                }
                if (i == j); // This comparison is always ignored.
                unique++; // This line is always happening
            }
        
            return unique;
        
        }
        

        【讨论】:

        • 对于问题中的输入仍然返回5
        • 非常感谢您的反馈,甚至没有注意到我跳过了括号..!
        【解决方案8】:

        你可以使用集合

        public static int numberOfUniqueIntegers(int[] number, int len) {
        
            Set<Integer> st = new HashSet();
            int unique = 0;
            for (int i = 0; i < len; i++) {
        
                if (!st.add(number[i])) {
                    unique = unique - 1;
                } else {
                    unique = unique + 1;
                }
            }
        
            return unique;
        }
        

        【讨论】:

        • 这将为{1, 1, 1}返回-1
        • 我这里用set只是因为复杂,应该是O(n)
        猜你喜欢
        • 1970-01-01
        • 2012-04-28
        • 1970-01-01
        • 1970-01-01
        • 2015-04-18
        • 1970-01-01
        • 1970-01-01
        • 2015-04-17
        • 1970-01-01
        相关资源
        最近更新 更多