How to find the number occurring an odd number of times in an array with Swift

1 Answer

0 votes
func oddOccurrence(in nums: [Int]) -> Int {
    // XOR all elements
    let xorValue = nums.reduce(0, ^)

    // Verify that this value actually appears
    return nums.first(where: { $0 == xorValue }) ?? -1
}

let arr = [2, 3, 7, 2, 8, 8, 8, 8, 3, 0, 0, 7, 7]

print(oddOccurrence(in: arr))


/*
run:

7

*/

 



answered Jan 30 by avibootz

Related questions

...