Tuesday 20 June 2017

How to get distinct elements from an array by avoiding duplicate elements?


Description:
The below example shows how to avoid duplicate elements from an array and disply only distinct elements. Please use only arrays to process it.

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.govindsblog.algos;
 
public class MyDisticntElements {
 
    public static void printDistinctElements(int[] arr){
         
        for(int i=0;i<arr.length;i++){
            boolean isDistinct = false;
            for(int j=0;j<i;j++){
                if(arr[i] == arr[j]){
                    isDistinct = true;
                    break;
                }
            }
            if(!isDistinct){
                System.out.print(arr[i]+" ");
            }
        }
    }
     
    public static void main(String a[]){
         
        int[] nums = {5,2,7,2,4,7,8,2,3};
        MyDisticntElements.printDistinctElements(nums);
    }
}

Output:
5 2 7 4 8 3 

No comments:

Post a Comment