「力扣」第 136 题: 只出现一次的数字


「力扣」第 136 题: 只出现一次的数字

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

说明:

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

示例 1:

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

示例 2:

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

Java 代码:

public class Solution {

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

    public static void main(String[] args) {
        int[] nums = {2, 2, 1};
        Solution solution = new Solution();
        int singleNumber = solution.singleNumber(nums);
        System.out.println(singleNumber);
    }
}

Java 代码:

public class Solution2 {

    public int singleNumber(int[] nums) {
        int len = nums.length;
        if (len == 0) {
            throw new RuntimeException("数组元素为空,没有只出现一次的数字");
        }

        int res = nums[0];
        for (int i = 1; i < len; i++) {
            res ^= nums[i];
        }
        return res;
    }
}

(本节完)


文章作者: liweiwei1419
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 liweiwei1419 !
评论
 上一篇
「力扣」第 137 题:只出现一次的数字 II 「力扣」第 137 题:只出现一次的数字 II
「力扣」第 137 题:只出现一次的数字 II 链接:https://leetcode-cn.com/problems/single-number-ii 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那
下一篇 
「力扣」第 125 题:验证回文串 「力扣」第 125 题:验证回文串
「力扣」第 125 题:验证回文串链接:https://leetcode-cn.com/problems/valid-palindrome 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 说明:本题中,我
  目录