博客
关于我
力扣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安装与常见命令
查看>>
Nginx安装及配置详解
查看>>
nginx安装配置
查看>>
Nginx实战经验分享:从小白到专家的成长历程!
查看>>
Nginx实现反向代理负载均衡
查看>>
nginx实现负载均衡
查看>>
nginx开机启动脚本
查看>>
nginx异常:the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf
查看>>
nginx总结及使用Docker创建nginx教程
查看>>
nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:128
查看>>
nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in usrlocalnginxconfnginx.conf128
查看>>
nginx日志分割并定期删除
查看>>
Nginx日志分析系统---ElasticStack(ELK)工作笔记001
查看>>
Nginx映射本地json文件,配置解决浏览器跨域问题,提供前端get请求模拟数据
查看>>
nginx最最最详细教程来了
查看>>
Nginx服务器---正向代理
查看>>
Nginx服务器上安装SSL证书
查看>>
Nginx服务器基本配置
查看>>
Nginx服务器的安装
查看>>
Nginx模块 ngx_http_limit_conn_module 限制连接数
查看>>