首页 > 编程语言 > 详细

leetcode.136 获取数组中只出现一次的数字

时间:2019-12-30 10:00:09      阅读:87      评论:0      收藏:0      [点我收藏+]

题目描述: 给一个数组,数组中只有一个数字出现了一次,其他的数字都出现了两次,找到这个只出现一次的数字

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

思路:

通过异或运算来消除出现两次的数字,从而最终得到只出现一次的数字。

 

代码实现:

class Solution {
    public int singleNumber(int[] nums) {
        // 思路:
        // 采用异或运算,数组中只有一个数出现了一次,其他的都出现了两次
        // 那么可以通过异或,把所有出现偶数次的数字给消除,最后剩下的只有那一个出现一次的数字
        int res = nums[0];
        for(int i =1; i<nums.length; i++){
            res ^= nums[i];
        }
        return res;
    }
}

 

leetcode.136 获取数组中只出现一次的数字

原文:https://www.cnblogs.com/smallone/p/12117976.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!