Untitled

Anonymous
Plain Text
09/15/2025 4:58 PM
1.6 KB
11
Indexable
Never
package ARRAYS;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class SingleNum {

    /**
     *This class takes an array nums sorted in non-decreasing order. Every number in the array except one appears twice. Find the single number in the array.
     *
     *
     * Examples:
     * Input :nums = [1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6]
     * Output:4
     * Explanation: Only the number 4 appears once in the array.
     *
     * Input : nums = [1, 1, 3, 5, 5]
     * Output:3
     * Explanation: Only the number 3 appears once in the array.
     */

    public static int searchSingleElement(int[] nums){

        int num = 0;
        Map<Integer,Integer> findSingleElement = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            if (findSingleElement.containsKey(nums[i])) {
                findSingleElement.put(nums[i],findSingleElement.get(nums[i]) + 1);
            } else {
                findSingleElement.put(nums[i],0);
            }
        }
        for (Integer key : findSingleElement.keySet()) {
            if (findSingleElement.get(key) == 0){
                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("NUM -> " + searchSingleElement(arr));
    }
}
Editor is loading...
Leave a Comment