Missing number - 寻找缺失的那个数字

简介: 需求:给出一个int型数组,包含不重复的数字0, 1, 2, ..., n;找出缺失的数字; 如果输入是[0, 1, 2] 返回 3  输入数组 nums = [0, 1, 2, 4] ;应该返回 3 输入nums = [2, 0] ;应该返回 1 输入nums = [1, 0];应该返回 ...

需求:给出一个int型数组,包含不重复的数字0, 1, 2, ..., n;找出缺失的数字;

如果输入是[0, 1, 2] 返回 3 

输入数组 nums = [0, 1, 2, 4] ;应该返回 3

输入nums = [2, 0] ;应该返回 1

输入nums = [1, 0];应该返回 2 

方法1:先排序,再线性寻找

元素不一定按顺序排列;

先对数组进行排序,再按顺序寻找

import java.util.Arrays;

public class Solution {
    public int missingNumber(int[] nums) {
        Arrays.sort(nums);  // 先排序
        int index;
        for (index = 0; index < nums.length; index ++) {
            if (index!= nums[index]) {
                return index;
            }
        }
        return index;
    }
}

这个方法比较容易想到,但缺点是速度太慢

方法2:异或法

输入的数组中没有重复的元素,可以利用异或的特点进行处理

异或:不同为1,相同为0;

任何数与0异或都不变,例如:a^0 = a ; 

多个数之间的异或满足互换性,a^b^c = a^c^b = a^(b^c)

1.假设输入的数组是[0, 1, 3],应该返回2

可以指定一个数组[0, 1, 2, 3],这个数组包含缺失的那个数字x

这个指定的数组其实是满足预设条件的数组

x并不存在,只是占个位置;把它们的元素按位异或,即

0, 1, x, 3

0, 1, 2, 3

0^1^2^3^0^1^3 = 0^0^1^1^3^3^2 = 0^2 = 2   得到结果“2”

2.假设输入数组是[2, 0],用数组[0, 1, 2]做如下运算:

0^0^1^2^2 = 1  得到结果 “1”

3.假设输入数组是[0, 1, 2, 3],指定一个数组[0, 1, 2, 3]用上面的方法计算

0^0^1^1^2^2^3^3 = 0  结果错误;实际应该返回4

我们用来计算的数组,也可以看做是输入数组的下标,再加1;这里应该用[0, 1, 2, 3, 4]来计算

0, 1, 2, 3, x

0, 1, 2, 3, 4          结果返回4

Java代码

public int missingNumber(int[] nums) {
    if(nums == null || nums.length == 0) {
        return 0;
    }
    int result = 0;
    for(int i = 0; i < nums.length; i++) {
        result ^= nums[i];
        result ^= i;
    }
    return result ^ nums.length;
}

代码中实现了前面说明的异或运算

目录
相关文章
|
11月前
|
C++ 容器
【PAT甲级 - C++题解】1144 The Missing Number
【PAT甲级 - C++题解】1144 The Missing Number
40 0
|
算法
LeetCode 268. Missing Number
给定一个包含 0, 1, 2, ..., n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。
63 0
LeetCode 268. Missing Number
【1144】The Missing Number (20 分)
【1144】The Missing Number (20 分) 【1144】The Missing Number (20 分)
69 0
LeetCode之Missing Number
LeetCode之Missing Number
66 0
|
算法
LeetCode 268 Missing Number(丢失的数字)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50768898 翻译 给定一个包含从0,1,2...,n中取出来的互不相同的数字,从数组中找出一个丢失的数字。
973 0
|
Java C++
[LeetCode] Missing Number
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. For example, Given nums = [0, 1, 3] return 2. Note: Your algorithm
1057 0
|
机器学习/深度学习 移动开发
[LeetCode] Missing Number
There are three methods to solve this problem: bit manipulation, rearrangement of the array, and math tricks.
646 0
|
6月前
|
算法
Leetcode 313. Super Ugly Number
题目翻译成中文是『超级丑数』,啥叫丑数?丑数就是素因子只有2,3,5的数,7 14 21不是丑数,因为他们都有7这个素数。 这里的超级丑数只是对丑数的一个扩展,超级丑数的素因子不再仅限于2 3 5,而是由题目给定一个素数数组。与朴素丑数算法相比,只是将素因子变了而已,解法还是和朴素丑数一致的。
65 1
|
1天前
|
存储 算法
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
4 0