136. Single Number

Problem:
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Analysis:

Use XOR, because any number XOR itself is 0. We can set result's initial value to 0, 0 XOR any number is that number. 

Solution:

 class Solution {
    public int singleNumber(int[] nums) {
        int res = 0;
        for (int n: nums) {
            res ^= n;
        }    
        return res;
    }
}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List