Untitled
unknown
plain_text
10 months ago
1.5 kB
12
Indexable
package ARRAYS;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class SingleElement {
/**
*This Class Takes an array nums where each integer in nums appears thrice except one. Find out the number that has appeared only once
*
* Examples:
* Input : nums = [2, 2, 2, 3]
* Output : 3
* Explanation : The integers 3 has appeared only once.
*
* Input : nums = [1, 0, 3, 0, 1, 1, 3, 3, 10, 0]
* Output : 10
* Explanation : The integers 10 has appeared only once.
*/
public static int searchSingleElement(int [] nums) {
Map<Integer,Integer> element = new HashMap<>();
int num = 0;
for (int i = 0; i < nums.length; i++) {
if (element.containsKey(nums[i])) {
element.put(nums[i],element.get(nums[i]) + 1);
} else {
element.put(nums[i],1);
}
}
for (Integer key : element.keySet()) {
if (element.get(key) == 1) {
num = key;
}
}
return num;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("ENTER ARRAY SIZE -> ");
int size = s.nextInt();
System.out.print("ENTER ARRAY ELEMENTS -> ");
int[] arr = new int [size];
for (int i = 0; i < size; i++) {
arr[i] = s.nextInt();
}
System.out.print("NUMBER -> -> " + searchSingleElement(arr));
}
}
Editor is loading...
Leave a Comment