LeetCode 136. Single Number

 

题目来源:https://leetcode.com/problems/single-number/

问题描述

136. Single Number

Easy

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

------------------------------------------------------------

题意

给定一个数组,除了一个元素,其他元素都出现了2次,求只出现了一次的那个元素。

------------------------------------------------------------

思路

解法1:哈希。用一个哈希表记录每个元素出现的次数,时间复杂度O(n),空间复杂度O(n)

解法2:位运算。利用异或运算的两条性质:

(1) 0 ^ x = x

(2) x ^ x = 0

(3) x ^ y ^ x = x ^ x ^ y = (x ^ x) ^ y = y(交换律)

将所有元素异或在一起,根据交换律,可以把所有重复出现的元素凑在一起变成0,最后剩下的就是只出现一次的元素。

时间复杂度O(n),空间复杂度O(1).

------------------------------------------------------------

代码

解法1:

class Solution {
    public int singleNumber(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int num: nums) {
            map.put(num, map.containsKey(num)? map.get(num)+1: 1);
        }
        for (int num: nums) {
            if (map.get(num) == 1) {
                return num;
            }
        }
        return -1;          // not found
    }
}

解法2:

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值