[英]Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique
[英]Return the number of unique number values in the array "arr"
我正在尋找一種方法來查找數組中唯一數值的數量。
我不能在這個項目中使用導入,但我可以使用循環和條件語句。
例如數組
int[] arr1 = {3, -3, -1, 0, -1, 4, 0, 3, 4, 0};
應該返回 5
這是我到目前為止的想法:
public static int countUniqueIntegers(int[] arr){
// Initialize int "counter" with value 0
int num_unique = 0;
// TO DO: Add logic to count unique values
if(arr.length == 0) return 0;
if(arr.length == 1) return 1;
double currentNumber = arr[0];
int currentCount =1;
for(int i =1; i < arr.length; i++)
{
if(arr[i] != currentNumber)
{
currentCount++;
currentNumber = arr[i];
}
}
// Return number of unique values
return num_unique;
}
我們可以假設數組中的每個值都是唯一的。 因此,開始時唯一值的數量與數組長度相同。 在此之后,我們必須將數組中的每個值與同一數組中的每個其他值進行比較。 為此,您需要在“for”循環中使用另一個“for”循環。 如果來自外部(第一個)循環的當前項目等於來自內部循環的某個項目,您只需從具有唯一數字計數的變量中減去 1(即開始時的數組長度)。
您現在要做的就是進行編程 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.