java - Finding Duplicates in Array and printing them only Once -
i trying loop through array , find numbers repeating more once:
e.g: if there 1 1 2 3 4
it should print saying "1 repeats more once"
here code , far have tried, prints duplicates , keep going, if there 4 4 4 4 3 6 5 6 9
, print 4's dont want that:
class average { public static void main(string[] args) throws ioexception { int numoflines = 0; int sum = 0, mean = 0, median = 0, lq = 0, uq = 0; int[] buffer; file myfile = new file("num.txt"); scanner scan = new scanner(myfile); while(scan.hasnextline()) { scan.nextline(); numoflines++; } scan.close(); scan = new scanner(myfile); system.out.println("number of lines: " + numoflines); buffer = new int[numoflines]; for(int i=0; i<numoflines; i++) { buffer[i] = scan.nextint(); } scan.close(); scan = new scanner(myfile); for(int i=0; i<buffer.length; i++) { sum = sum+i; mean = sum/numoflines; } system.out.println("sum: " + sum); system.out.println("mean: " + mean); for(int i=0; i<buffer.length; i++) { for(int k=i+1; k<buffer.length; k++) { if(buffer[k] == buffer[i]) { system.out.println(buffer[k]); } } }
just add number find duplicated structure hashset
or hashmap
can find later when detect duplication.
set<integer> printed = new hashset<integer>(); for(int i=0; i<buffer.length; i++) { for(int k=i+1; k<buffer.length; k++) { if(buffer[k] == buffer[i]) { integer intobj = new integer(buffer[k]); if (!printed.contains(intobj)) { system.out.println(buffer[k]); printed.add(intobj); } break; } } }
better o(n) alghorithm:
set<integer> printed = new hashset<integer>(); for(int i=0; i<buffer.length; i++) { if (!printed.add(new integer(buffer[i])) { system.out.println(buffer[i]); } }
Comments
Post a Comment