Data Structures and Algorithms "two"

Only one truth, it is not religion, but in science. --- Leonardo da Vinci

LeetCode: only once digital

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:

  • Using a linear time complexity, no additional space.

Example:

输入: [2,2,1]
输出: 1

analysis:

Because of limited time and space complexity, and obviously can not traverse twice the other open space, this inspection bit operation, the number of two identical XOR operation result is 0, since in addition to an array element appears only once in addition, other elements appear twice, if all the numbers are different or the same number XOR to zero, and finally left a number appears under it and 0 XOR, the result is that it itself.

Code:

class Solution {
    public int singleNumber(int[] nums) {
        int num = 0;
        for(int i = 0; i < nums.length; i++){
            num = num ^ nums[i];
        }
        return num;
    }
}

Regularly share large data and knowledge map knowledge points:
Micro-channel public number

Guess you like

Origin www.cnblogs.com/zeppelin/p/11068218.html