Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding non duplicate element in an array

Tags:

java

arrays

I am stuck in the following program:

I have an input integer array which has only one non duplicate number, say {1,1,3,2,3}. The output should show the non duplicate element i.e. 2.

So far I did the following:

public class Solution {

    public int singleNumber(int[] arr){
        int size = arr.length;
        int temp = 0;
        int result = 0;
        boolean flag = true;
        int[] arr1 = new int[size];

        for(int i=0;i<size;i++){
            temp = arr[i];
            for(int j=0;j<size;j++){
                if(temp == arr[j]){
                    if(i != j)
                    //System.out.println("Match found for "+temp);
                    flag = false;
                    break;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {

        int[] a = {1,1,3,2,3};
        Solution sol = new Solution();

        System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
    }
}

Restricting the solution in array is preferable. Avoid using collections,maps.

like image 693
Leo Avatar asked Dec 31 '14 13:12

Leo


3 Answers

public class NonRepeatingElement {

public static void main(String[] args) {

    int result =0;
    int []arr={3,4,5,3,4,5,6};
    for(int i:arr)
    {
        result ^=i;
    }

    System.out.println("Result is "+result);
}

}
like image 135
user7258708 Avatar answered Oct 14 '22 17:10

user7258708


Since this is almost certainly a learning exercise, and because you are very close to completing it right, here are the things that you need to change to make it work:

  • Move the declaration of flag inside the outer loop - the flag needs to be set to true every iteration of the outer loop, and it is not used anywhere outside the outer loop.
  • Check the flag when the inner loop completes - if the flag remains true, you have found a unique number; return it.
like image 20
Sergey Kalinichenko Avatar answered Oct 14 '22 18:10

Sergey Kalinichenko


From Above here is the none duplicated example in Apple swift 2.0

func noneDuplicated(){    
            let arr = [1,4,3,7,3]    
                 let size = arr.count  
                 var temp = 0  
                 for i in 0..<size{  
                   var flag = true  
                   temp = arr[i]  
                     for j in 0..<size{  
                     if(temp == arr[j]){  
                        if(i != j){  
                            flag = false  
                            break  
                        }   
                    }   
                }    
                if(flag == true){   
                print(temp + " ,")   
                }  
            }  
        }

// output : 1 , 4 ,7
// this will print each none duplicated 
like image 43
Pankaj Bhardwaj Avatar answered Oct 14 '22 17:10

Pankaj Bhardwaj