Java O(N) runtime O(1) space -with bit manipulation


  • 0
    G
    public class Solution {
        public int[] findErrorNums(int[] nums) {
             
            int xorOrg = 
            IntStream.range(1,nums.length + 1).reduce(0,(i,j)->i^j);
            
            int xorOther = 
            IntStream.range(0,nums.length).map(i->nums[i]).reduce(0,(i,j)->i^j);
            
            int xorAll = xorOrg ^ xorOther;
            
            int bit = xorAll & ~(xorAll - 1);
            
            int xorFirstOrg = 
            IntStream.range(1,nums.length + 1).filter(i->((i & bit) != 0)).reduce(0,(i,j)->i ^ j);
            
            int xorSecOrg = 
            IntStream.range(1,nums.length + 1).filter(i->((i & bit) == 0)).reduce(0,(i,j)->i ^ j);
            
            int xorFirstOther = 
            IntStream.range(0,nums.length).map(i->nums[i]).filter(i->((i & bit) != 0)).reduce(0,(i,j)->i ^ j);
            
            int xorSecOther = 
            IntStream.range(0,nums.length).map(i->nums[i]).filter(i->((i & bit) == 0)).reduce(0,(i,j)->i ^ j);
                                               
            int one = xorFirstOrg ^ xorFirstOther;
            int second = xorSecOrg ^ xorSecOther;
                    
            int [] res = new int[2];
                                               
            for(int i = 0; i < nums.length; ++i){
                if(nums[i] == one){
                    res[0] = one;
                    res[1] = second;
                    break;
                }
                else if(nums[i] == second){
                    res[0] = second;
                    res[1] = one;
                    break;
                }
            }
            
            return res;
        }
    }
    

Log in to reply
 

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