返回数组“arr”中唯一数值的数目

vsaztqbk  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(484)

我正在寻找一种方法来查找数组中唯一数值的数目。
我不能为这个项目使用导入,但我可以使用循环和条件语句。
例如数组

  1. int[] arr1 = {3, -3, -1, 0, -1, 4, 0, 3, 4, 0};

应该返回5
到目前为止,我想到的是:

  1. public static int countUniqueIntegers(int[] arr){
  2. // Initialize int "counter" with value 0
  3. int num_unique = 0;
  4. // TO DO: Add logic to count unique values
  5. if(arr.length == 0) return 0;
  6. if(arr.length == 1) return 1;
  7. double currentNumber = arr[0];
  8. int currentCount =1;
  9. for(int i =1; i < arr.length; i++)
  10. {
  11. if(arr[i] != currentNumber)
  12. {
  13. currentCount++;
  14. currentNumber = arr[i];
  15. }
  16. }
  17. // Return number of unique values
  18. return num_unique;
  19. }
eqfvzcg8

eqfvzcg81#

我们可以先假设数组中的每个值都是唯一的。因此,开始处唯一值的数目与数组长度相同。在此之后,我们必须将数组中的每个值与同一数组中的其他值进行比较。为此,您需要另一个“for”循环内的“for”循环。如果来自外部(第一个)循环的当前项等于来自内部循环的某个项,则只需从具有唯一数字计数的变量中减去1(即开始处的数组长度)。
你现在要做的就是编程:)

相关问题