How to find all odd occurring elements in an array in JAVA -
i trying find elements occur odd number of times in array. worked out little bit, code returning correct answer if there 1 number occurs odd number of times. if there 2 or more odd occurring numbers not able process it. understand if bit-wise xor of elements 1 odd occurring element. how can improve multiple numbers?
below code:
public class oddoccur { public int oddoccurence(int[] arr, int size) { int res = 0; int[] fin = new int[size]; (int = 0; < size; i++) { res = res ^ arr[i]; } return res; } public static void main(string args[]) { int[] arr = { 2, 5, 5, 2, 2, 3, 3, 3 }; int n = arr.length; oddoccur obj = new oddoccur(); system.out.println("odd occuring element is:" + obj.oddoccurence(arr, n)); } }
need solve issue!
public int oddoccurence(int[] arr, int size);
first, there can multiple numbers occur odd number of times. there's no way write function , make work if returns single int
. you'll need function can return multiple numbers.
public int[] oddoccurrences(int[] array);
second, don't try clever. using xor "clever". you're not going find simple solution using xor. it'll convoluted, complicated mess. keep simple:
- count number of times each number appears.
- then find odd counts.
example pseudo-code:
// map numbers counts. assume counts start @ 0. map<integer, integer> counts; (number in array) { counts[number] += 1 } // list of numbers occur odd number of items. list<integer> oddnumbers; (number, count in counts) { if (count % 2 != 0) { oddnumbers.add(number); } }
Comments
Post a Comment