博客
关于我
力扣LeetCode 268. 缺失数字
阅读量:273 次
发布时间:2019-03-01

本文共 527 字,大约阅读时间需要 1 分钟。

题目

给定一个包含 0, 1, 2, …, n 中 n 个数的序列,找出 0 … n 中没有出现在序列中的那个数。

示例1

输入: [3,0,1]

输出: 2

示例2

输入: [9,6,4,2,3,5,7,0,1]

输出: 8

示例3

输入: [0]

输出: 1

题解

因为序列是[0, n],而每个序列都少了一个数,所以给定的数n就是数组长度。

借鉴评论区大佬的思路
首先要明白安按位异或(^):两个数值的二进制位上的值不相同,则结果为1
如 3^1 = 11^01 = 10 = 2
而 3^3 = 11^11 = 00 = 0
所以假设某一元素为x,则有 x^x=9, x^0=x
代码:

public int missingNumber(int[] nums) {   	int res = nums.length;	for (int i = 0; i < nums.length; ++i){   		res ^= nums[i];		res ^= i;	}	return res;}

例如,对于数组[3,2,0,1],将循环语句的式子列出来为:

4^3^0^2^1^0^2^1^3 = 0^0^1^1^2^2^3^3^4 = 4
所以答案为4

转载地址:http://tmmx.baihongyu.com/

你可能感兴趣的文章
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named 'pandads'
查看>>