Computer Science, asked by adityase6078caltech, 7 months ago

write a java program to input 15 integer elements in 1d array and print only those elements which are perfect elements of the array​

Answers

Answered by Anonymous
1

Answer:

Print All Distinct Elements of a given integer array

Approach:

1. Put all input integers to hashmap’s key

2. Print keySet outside the loop

Java

import java.util.HashMap;

public class UniqueInArray2 {

public static void main(String args[])

{

int ar[] = { 10, 5, 3, 4, 3, 5, 6 };

HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();

for (int i = 0; i < ar.length; i++) {

hm.put(ar[i], i);

}

// Using hm.keySet() to print output reduces time complexity. - Lokesh

System.out.println(hm.keySet());

}

}

Given an integer array, print all distinct elements in array. The given array may contain duplicates and the output should print every element only once. The given array is not sorted.

Examples:

Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}

Output: 12, 10, 9, 45, 2

Input: arr[] = {1, 2, 3, 4, 5}

Output: 1, 2, 3, 4, 5

Input: arr[] = {1, 1, 1, 1, 1}

Output: 1

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

A Simple Solution is to use twp nested loops. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the element is present on left side of it. If present, then ignores the element, else prints the element. Following is the implementation of the simple algorithm.

C++

// C++ program to print all distinct elements in a given array

#include <bits/stdc++.h>

using namespace std;

void printDistinct(int arr[], int n)

{

// Pick all elements one by one

for (int i=0; i<n; i++)

{

// Check if the picked element is already printed

int j;

for (j=0; j<i; j++)

if (arr[i] == arr[j])

break;

// If not printed earlier, then print it

if (i == j)

cout << arr[i] << " ";

}

}

// Driver program to test above function

int main()

{

int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};

int n = sizeof(arr)/sizeof(arr[0]);

printDistinct(arr, n);

return 0;

}

Similar questions