博客
关于我
力扣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/

你可能感兴趣的文章
mysql 1593_Linux高可用(HA)之MySQL主从复制中出现1593错误码的低级错误
查看>>
mysql 5.6 修改端口_mysql5.6.24怎么修改端口号
查看>>
MySQL 8.0 恢复孤立文件每表ibd文件
查看>>
MySQL 8.0开始Group by不再排序
查看>>
mysql ansi nulls_SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思
查看>>
multi swiper bug solution
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
mysql client library_MySQL数据库之zabbix3.x安装出现“configure: error: Not found mysqlclient library”的解决办法...
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>