Sunday, July 26, 2015

Find Single Number


Problem : Given an array of integers, every element appears twice except one. Find that single one in linear time. Can you do it in without using extra memory ?
Basic idea is to scan the array you take a xor of each element. Duplicate elements will cancel each other.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class Solution {
    public int singleNumber(int[] nums) {
        
        if(nums == null){
            return 0;
        }
        if(nums.length == 1){
            return nums[0];
        }
        int result =0;
        for(int i=0; i < nums.length; i++){
            result = result^nums[i];
        }
        
        return result;
    }
}

No comments:

Post a Comment