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

你可能感兴趣的文章
nginx+php的搭建
查看>>
nginx+tomcat+memcached
查看>>
Nginx+Tomcat实现动静分离
查看>>
nginx+Tomcat性能监控
查看>>
nginx+uwsgi+django
查看>>
nginx+vsftp搭建图片服务器
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>
Nginx/Apache反向代理
查看>>
Nginx: 413 – Request Entity Too Large Error and Solution
查看>>
nginx: [emerg] getpwnam(“www”) failed 错误处理方法
查看>>
nginx: [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:
查看>>
nginx:Error ./configure: error: the HTTP rewrite module requires the PCRE library
查看>>
Nginx:objs/Makefile:432: recipe for target ‘objs/src/core/ngx_murmurhash.o‘解决方法
查看>>
Nginx、HAProxy、LVS
查看>>
Nginx下配置codeigniter框架方法
查看>>
Nginx中使用expires指令实现配置浏览器缓存
查看>>
nginx中配置root和alias的区别
查看>>
nginx主要流程(未完成)
查看>>
Nginx之二:nginx.conf简单配置(参数详解)
查看>>