Simple java solution with Xor operator with O(n) and O(1) space run time 11 ms


  • 0
    N
    public class Solution {
        public int[] findErrorNums(int[] nums) {
            int xor = 0;
            for(int i =0; i< nums.length;i++){
                xor^= nums[i];
            }
            
            for(int i=1; i<=nums.length;i++){
                xor^=i;
            }
            
            int setbit = (xor & ~(xor-1));        
            int first = 0; int second =0;
            for(int i =0; i<nums.length;i++){
                if((nums[i] &setbit)!=0){
                    first ^= nums[i];
                }else{
                    second ^= nums[i]; 
                }
            }
            
            for(int i =1; i<= nums.length; i++){
                if((i & setbit)!=0){
                    first ^= i;
                }else{
                    second ^= i; 
                }
            }
            
            for(int i =0;i< nums.length;i++)
            {
                if((nums[i]^ first)==0){
                    return new int[]{first,second};
                }else if((nums[i]^second )==0){
                    return new int[]{second,first};
                }
            }
            return new int[]{first, second};
        }
    }
    

    Reference :-http://www.geeksforgeeks.org/find-the-two-repeating-elements-in-a-given-array/


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.