LeetCode(136)-Single Number(单数异或实现)

    xiaoxiao2022-12-07  51

    题目:

    Given a non-empty 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?

    Example 1:

    Input: [2,2,1] Output: 1 Example 2:

    Input: [4,1,2,1,2] Output: 4

    翻译:

    给定一个非空整数数组,除一个元素外,每个元素都出现两次。找到那一个。 注意: 您的算法应该具有线性运行时复杂度。你能在不使用额外内存的情况下实现它吗? 示例1: 输入(2 2 1): 输出:1 示例2: 输入:[4、1、2、1、2) 输出:4

    思路:

    这道题我们采用异或的概念进行处理,两个相同的数字异或的结果为0,本题的数组中,除了一个元素外,其它元素都是两两一样,那么将元素全部异或后,其结果就为单独那个元素。

    代码实现:

    class Solution { public int singleNumber(int[] nums) { if(nums==null || nums.length==0) return 0; int num=0; for(int n:nums){ num^=n; } return num; } }
    最新回复(0)