美文网首页工作生活LeetCode
只出现一次的数字

只出现一次的数字

作者: 习惯了_就好 | 来源:发表于2019-07-04 09:04 被阅读0次

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

说明:

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

示例 1:

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

示例 2:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
    public int singleNumber(int[] nums) {
        //万能的暴力法
        int length = nums.length;
        for(int i = 0; i < length; i++){
            int num = nums[i];
            boolean isOnly = true;
            for(int j = 0; j < length; j++){
                if(i != j && num == nums[j]){
                    isOnly = false;
                    break;
                }
            }
            if(isOnly){
                return num;
            }
        }
        return -1;
    }
}

class Solution {
//使用map,最终存放为1的是
    public int singleNumber(int[] nums) {
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        int length = nums.length;
        for(int i = 0; i < length; i++){
            int num = nums[i];
            if(map.get(num) != null){
                map.put(num,2);
            } else {
                map.put(num,1);
            }
        }
        
        for(int key : map.keySet()){
            if(map.get(key) == 1){
                return key;
            }
        }
        return -1;
    }
}
//官方的位操作解析
//
 //  如果我们对 0 和二进制位做 XOR 运算,得到的仍然是这个二进制位
 //       a⊕0=aa \oplus 0 = aa⊕0=a
 //   如果我们对相同的二进制位做 XOR 运算,返回的结果是 0
 //       a⊕a=0a \oplus a = 0a⊕a=0
 //   XOR 满足交换律和结合律
//        a⊕b⊕a=(a⊕a)⊕b=0⊕b=ba \oplus b \oplus a = (a \oplus a) \oplus b = 0 \oplus b = ba⊕b⊕a=(a⊕a)⊕b=0⊕b=b
//
//所以我们只需要将所有的数进行 XOR 操作,得到那个唯一的数字。

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

相关文章

网友评论

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

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