Array with loops Java -
i want print put elements in array occur twice. if, example, number 2 occurs 3 or 4 times, should not printed. code i've written far below. issue in code loop. example, number 2, since j=i+1
initialization condition, inner loop won't read elements before j
th location- since there 2 @ index 6, won't count 2s before it, making required condition true , displaying 2. there way fix this?
public class problem2 { public static void exactlytwice(int[] x) { int count, j; (int = 0; < x.length; i++) { count = 0; (j = + 1; j < x.length; j++) { if (x[i] == x[j]) count++; } if (count == 1) system.out.print(x[i] + " "); } } public static void main(string[] args) { int[] x = new int[15]; x[0] = 2; x[1] = 2; x[2] = 2; x[3] = 13; x[4] = 44; x[5] = 44; x[6] = 2; x[7] = 63; x[8] = 63; x[9] = 90; x[10] = 1; x[11] = 2; x[12] = 150; x[13] = 150; x[14] = 180; exactlytwice(x); } }
aside issue wrote, bigger problem see code inefficient. doing loop inside loop here, slow (o(n^2)).
my suggestion keep map of numbers->count, , take ones appear twice in map:
public static void exactlytwice(int[] x) { map<integer, integer> counter = new hashmap<>(); (int = 0; < x.length; i++) { if (counter.contains(i)) { counter.put(i,1); } else { counter.put(i,counter.get(i)+1); } } (integer : counter.keyset()) { if (counter.get(i) == 2) { system.out.println(i); } } }
Comments
Post a Comment