One line Java solution with #Stream and #XOR


  • 1

    Same idea with other bit manipulation solutions but with the Java8 stream API.

    public class Solution {
        public int singleNumber(int[] nums) {
            return IntStream.of(nums).reduce((n1, n2) -> n1^n2).orElse(Integer.MAX_VALUE);
        }
    }
    

  • 1

    Compared with the solution without using the stream API.

    public class Solution {
        public int singleNumber(int[] nums) {
            int r = 0; // XOR is safe to begin with 0
            for(int i=0;i<nums.length;++i) r^=nums[i];
            return r;
        }
    }
    

Log in to reply
 

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