How can I find the number of unique values of a String array?
e.g.
double a[] = {aab,aba,aca,aab,adc,zzz,aca};
How can I get 2?
Many thank
Printable View
How can I find the number of unique values of a String array?
e.g.
double a[] = {aab,aba,aca,aab,adc,zzz,aca};
How can I get 2?
Many thank
What classes and methods can you use for this?
Sort the array and then scan it
Use a Map to keep a count of the occurences of each value then scan it
eRaaaa You could explain how your very clever code works in case the OP is a beginner and not familiar with the techniques you are using.
Does your code produce the correct answer? See next post.
Go thru the list adding one to count if unique, subtracting 1 if a duplicate:
"aab", 1
"aba", 2
"aca", 3
"aab", 2 (-1 because a dup)
"adc", 3
"zzz", 4
"aca" 3 (-1 dup)
Are there 2 or 3 unique elements in the list? aba, adc and zzz
Sorry this is the full question:
Create a static method called countUnique(String s[]) that accepts an array of strings as a parameter and returns the number of unique strings in the array. A unique string would be a string that occurs only once in the array. For example countUnique(new int[]{“aaa”,”aba”,”aba”,”ccc”}) would return 2 as there are 2 unique strings in the array: “aaa” and “ccc”
I think better to put it in set. then set will not allow duplicates so u can get unique values and count those elament su can get 2.