Java Solution #bit-manipulation #stream


  • 1

    This is a typical solution by bit manipulation with a detailed explanation here, but using Java8's stream APIs.

    public class Solution {
        public int[] singleNumber(int[] nums) {
            
            int xorAll = IntStream.of(nums).reduce((o1, o2)->o1^o2).orElse(0);
            
            int mask = xorAll & ~(xorAll - 1);
            
            int[] result = new int[2];
            int num1 = IntStream.of(nums).filter(num->(num&mask)==0).reduce((o1, o2)->o1^o2).orElse(0);
            int num2 = IntStream.of(nums).filter(num->(num&mask)!=0).reduce((o1, o2)->o1^o2).orElse(0);
            
            return new int[]{num1, num2};
        }
    }
    

  • 1

    It would be better if we create a stream supplier according to this post:
    https://stackoverflow.com/questions/36255007/is-there-any-way-to-reuse-a-stream-in-java-8


Log in to reply
 

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