136 number appears only once

Title Description

Given a non-empty array of integers, in addition to an element appears only once, the rest of each element appears twice. To find out that only appears once in the elements.

Description:

Your algorithm should have linear time complexity. You can not use the extra space to achieve it?

Ideas analysis

  • The simplest use HashMap exist, exist, remove the last remaining is the desired number
  • No auxiliary space, or to use different features, a different number equal to 0 or yourself, the last remaining exclusive or the entire array is to be digital.
  • This question has appeared as two Advanced only once. 104 496 036

Code

    public int singleNumber(int[] nums) {
        int ret = 0;
        for (int i = 0; i < nums.length; i++) {
            ret ^= nums[i];
        }
        return ret;
    }
Published 117 original articles · won praise 8 · views 3693

Guess you like

Origin blog.csdn.net/qq_34761012/article/details/104600158