美文网首页
LeetCode-只出现一次的数字

LeetCode-只出现一次的数字

作者: G_dalx | 来源:发表于2018-09-02 21:41 被阅读0次

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

说明:

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

示例 1:

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

示例 2:

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

思考:算法具有线性复杂度说明不能使用两层For循环,联想Map使用键值对记录每个元素和它出现的次数
最后输出次数为一的元素
代码:

class Solution {    
public  int singleNumber(int[] nums) {
        int i = 0;
        int j = nums.length - 1;
        Map<Integer, Integer> map = new HashMap<>();
        while (i <= j) {
            if (map.containsKey(nums[i]))
                map.put(nums[i], map.get(nums[i])+1);
            else
                map.put(nums[i], 1);
            i++;            
        }
        i = 0;
        while (i <= j) {
            if (map.get(nums[i]) == 1)
                break;
            i++;
        }
        return nums[i];
    }
}

虽然通过了,但是看大神的算法看的不是很懂,所以copy了一份大神的代码与解释
解法:位运算
使用异或运算:
如果a、b两个值不相同,则异或结果为1。如果a、b两个值相同,异或结果为0。
0与任何数做异或都是 那个数,相同的数字做异或等于0;
如:

    1. a ^ b = b ^ a
    2. a ^ b ^ c = a ^ (b ^ c) = (a ^ b) ^ c;

代码:

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

虽然说在实际开发中这样的用法并不多见,但是也是打开了一种思路。

相关文章

网友评论

      本文标题:LeetCode-只出现一次的数字

      本文链接:https://www.haomeiwen.com/subject/hjcvwftx.html