LeetCode: 只出现一次的数字

2018-08-13  本文已影响14人  慕剑璃

只出现一次的数字


给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。


Example

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

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


Note

你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

Answer Here

/**
 * <p>Given a non-empty array of integers, 
 * every element appears twice except for one. 
 * Find that single one.</p>
 *
 * <p>Notes:</p>
 * <p>In-space : without using extra memory.</p>
 * <p>In-time  : a liner runtime complexity.</p>
 *
 * @author Loucianus
 * @version 1.0
 */
public class SingleNumber {

    /**
     * Find that single one.
     *
     * A number XOR itself cloud get ZERO.
     * There must is the single one number in that array.
     * So we can nums[0] XOR nums[1] XOR ...XOR nums[length - 1],then we can get the single one;
     *
     * @param nums the array :{@code nums} of integer that we need to find the single number.
     * @return that single number in the array :{@code nums}
     */
    public int singleNumber(int[] nums) {

        int single = 0;

        for (int num : nums) {
            single = single ^ num;
        }
        return single;
    }
}

Thinking

利用异或运算,一个数异或自己本身得0。
因为数组中只有一个不同的数。
故将数组每一个元素异或之后就会就会变成那个只有一个的数

上一篇 下一篇

猜你喜欢

热点阅读