LeetCode Single Number

原题链接在这里:https://leetcode.com/problems/single-number/


首先会想到HashMap,HashSet的想法,但会用到extra O(n) space.

所以就要用到bit manipulation,这里和Single Number II非常相似,就不复述了。

但这里有个更快的方法,就是用异或 ^ operator. 异或 every number in the array and the result would be the single number.

Note: 1. 函数返回的是int,corner case 不能返回null,否则会报错。

2. 在写嵌套循环时,注意不要搞混 i , j 的含义。


AC Java:

public class Solution {
    public int singleNumber(int[] nums) {
        /*Method 1
        if(nums == null || nums.length == 0)
            return Integer.MIN_VALUE;
        
        HashSet hs = new HashSet();
        for(int i = 0; i < nums.length; i++){
            if(!hs.contains(nums[i])){
                hs.add(nums[i]);
            }else{
                hs.remove(nums[i]);
            }
        }
        
        Iterator it = hs.iterator();
        int res = Integer.MIN_VALUE;
        while(it.hasNext()){
            res = (int)it.next();
        }
        
        return res;
        */
        
        /*Method 2
        if(nums == null || nums.length == 0)
            return Integer.MIN_VALUE;
            
        int [] bitCounter = new int[32];
        for(int i = 0; i<32; i++){
            for(int j = 0; j<nums.length; j++){
                bitCounter[i] += (nums[j]>>i&1); //error
            }
        }
        int res = 0;
        for(int i = 0; i<32; i++){
            res += (bitCounter[i]%2)<<i;
        }
        return res;
        */
        
        //Method 3
        if(nums == null || nums.length == 0)
            return Integer.MIN_VALUE;
        int res = 0;
        for(int j = 0; j < nums.length; j++){
            res = res ^ nums[j];
        }
        return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值