In: Computer Science
numUnique returns the number of unique values the list * Precondition: the list is not empty and is sorted from low to high. * { your solution can assume this is true } * * For full credit, your solution must go through the list exactly once. * Your solution may not call any other functions. * * Examples: * { abcdef }.numUnique() == 6 * { aaabcd }.numUnique() == 4 * { bccddee }.numUnique() == 4 * { abcddd }.numUnique() == 4 * { a }.numUnique() == 1
FOR JAVA
Main.java
import java.util.*;
public class Main
{
public static int numUnique(List<String> list){
/* First element always be unique so count is set to 1 */
int count=1;
/* First element is taken as temp to compare with following
element to find next unique element*/
String temp = list.get(0);
for (int i = 1; i < list.size(); i++) {
if(!temp.equals(list.get(i))){
/*When next unique elememt is found count will be increased
and new element will be set as temp to compare with following
element */
count++;
temp = list.get(i);
}
}
return count;
}
public static void main(String[] args) {
List<String> list=new ArrayList<String>();
list.add("a");
list.add("a");
list.add("a");
list.add("b");
list.add("c");
//list.add("c");
list.add("d");
//list.add("d");
//list.add("d");
//list.add("d");
//list.add("e");
//list.add("e");
System.out.println(numUnique(list));
}
}
Code Snippet (For Indentation):
Output