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

你可能感兴趣的文章
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No static resource favicon.ico.
查看>>
no such file or directory AndroidManifest.xml
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
no1
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
node
查看>>
node exporter完整版
查看>>
node HelloWorld入门篇
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node JS: < 二> Node JS例子解析
查看>>
Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime(93)解决
查看>>
Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
查看>>
Node 裁切图片的方法
查看>>
node+express+mysql 实现登陆注册
查看>>