面试题17.04.消失的数字
题目描述
数组nums包含从0到n的所有整数,但其中缺了一个。请编写代码找出那个缺失的整数。你有办法在O(n)时间内完成吗?
输入输出样式
示例1:
输入:[3,0,1]
输出:2
示例2:
输入:[9,6,4,2,3,5,7,0,1]
输出:8
本文题来自LeetCode:https://leetcode-cn.com/problems/missing-number-lcci/
思路
- 先排序,然后遍历一遍数组找出缺失的元素,但是超时了。
- 用位运算—异或运算^;利用了异或的特点:对同一个值异或两次,结果为本身,比如:x ^ y ^ y = x;所以这里的思路即把所有的索引值异或到一起,然后在分别异或数组内的元素,这样存在的元素就一一抵消,剩下的就是要寻找的不存在的元素。举例:x = x ^ a ^ b ^ c ^ … ^ z;然后假设c元素不存在,再用x ^ a ^ b ^ d ^ … ^ z结果就是c了。
算法分析
- 时间复杂度为O(NlogN),空间复杂度为O(1)
- 时间复杂度为O(N),空间复杂度为O(1)
求解函数
//方法一:排序,再遍历一遍寻找
public int missingNumber(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length; ++i){
if (nums[i] != i){
return i;
}
}
return nums.length;
}
public int missingNumber(int[] nums) {
//方法二: 位运算--异或
int rst = nums.length;
for (int i = 0; i < nums.length; ++i){
rst ^= i;
rst ^= nums[i];
}
return rst;
}
主函数调用
import java.util.Arrays;
class Solution1704 {
public static void main(String[] args) {
int[] nums = new int[]{0,1};
Solution1704 sol = new Solution1704();
System.out.println(sol.missingNumber(nums));
}
public int missingNumber(int[] nums) {...}
}