【Lintcode】237. Missing Integer

题目地址:

https://www.lintcode.com/problem/missing-integer/description

给定一个长度为 n n n的数组,内含的数字是 0 ∼ n 0\sim n 0n,但缺且仅缺 1 1 1个。将其求出。题目中的数组元素都是一个叫BitInteger的类,其本质是一个 32 32 32位整数,提供了一个方法返回其右起第 i i i位是 0 0 0还是 1 1 1,其中 i i i 0 0 0开始计数。

注意到所有 32 32 32位整数关于异或运算形成一个阿贝尔群,且每个元素阶都为 2 2 2(除了 0 0 0的阶是 1 1 1),单位元为 0 0 0(证明参见https://blog.csdn.net/qq_46105170/article/details/104082406),我们想到将所有数组中的数字都异或一遍,再与 1 ∼ n 1\sim n 1n异或一遍,即得结果。代码如下:

import java.util.List;

public class Solution {
    /**
     * @param array a BitInteger list
     * @return an integer
     */
    public int findMissing(List<BitInteger> array) {
        // Write your code here
        int res = 0;
    
        for (BitInteger bitInteger : array) {
            for (int j = 0; j < 32; j++) {
                res ^= bitInteger.fetch(j) << j;
            }
        }
    
        for (int i = 0; i < array.size(); i++) {
            res ^= i + 1;
        }
        
        return res;
    }
}

class BitInteger {
    public static int INTEGER_SIZE = 31;
    public int fetch(int j) {
        .... // return 0 or 1, fetch the jth bit of this number
    }
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
error C2143: syntax error : missing ';' before 'type' C:\Users\lenvo\Desktop\CUITc语言题库答案\P237.C(11) : error C2143: syntax error : missing ';' before 'type' C:\Users\lenvo\Desktop\CUITc语言题库答案\P237.C(13) : error C2065: 'i' : undeclared identifier C:\Users\lenvo\Desktop\CUITc语言题库答案\P237.C(14) : error C2065: 'j' : undeclared identifier C:\Users\lenvo\Desktop\CUITc语言题库答案\P237.C(16) : error C2065: 'arr' : undeclared identifier C:\Users\lenvo\Desktop\CUITc语言题库答案\P237.C(16) : error C2109: subscript requires array or pointer type C:\Users\lenvo\Desktop\CUITc语言题库答案\P237.C(16) : error C2109: subscript requires array or pointer type C:\Users\lenvo\Desktop\CUITc语言题库答案\P237.C(16) : error C2102: '&' requires l-value C:\Users\lenvo\Desktop\CUITc语言题库答案\P237.C(18) : error C2065: 'sum' : undeclared identifier C:\Users\lenvo\Desktop\CUITc语言题库答案\P237.C(18) : error C2109: subscript requires array or pointer type C:\Users\lenvo\Desktop\CUITc语言题库答案\P237.C(18) : error C2109: subscript requires array or pointer type C:\Users\lenvo\Desktop\CUITc语言题库答案\P237.C(18) : error C2109: subscript requires array or pointer type C:\Users\lenvo\Desktop\CUITc语言题库答案\P237.C(18) : error C2109: subscript requires array or pointer type C:\Users\lenvo\Desktop\CUITc语言题库答案\P237.C(18) : error C2109: subscript requires array or pointer type C:\Users\lenvo\Desktop\CUITc语言题库答案\P237.C(18) : error C2109: subscript requires array or pointer type
最新发布
04-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值