​LeetCode刷题实战268:丢失的数字

程序IT圈

共 1396字,需浏览 3分钟

 ·

2021-05-19 13:12

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 丢失的数字,我们先来看题面:https://leetcode-cn.com/problems/missing-number/

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.


Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?

给定一个包含 [0, n] 中 n 个数的数组 nums ,找出 [0, n] 这个范围内没有出现在数组中的那个数。进阶:你能否实现线性时间复杂度、仅使用额外常数空间的算法解决此问题?

示例


示例 1:

输入:nums = [3,0,1]
输出:2
解释:n = 3,因为有 3 个数字,所以所有的数字都在范围 [0,3] 内。2 是丢失的数字,因为它没有出现在 nums 中。

示例 2:

输入:nums = [0,1]
输出:2
解释:n = 2,因为有 2 个数字,所以所有的数字都在范围 [0,2] 内。2 是丢失的数字,因为它没有出现在 nums 中。

示例 3:

输入:nums = [9,6,4,2,3,5,7,0,1]
输出:8
解释:n = 9,因为有 9 个数字,所以所有的数字都在范围 [0,9] 内。8 是丢失的数字,因为它没有出现在 nums 中。

示例 4:

输入:nums = [0]
输出:1
解释:n = 1,因为有 1 个数字,所以所有的数字都在范围 [0,1] 内。1 是丢失的数字,因为它没有出现在 nums 中。


解题


这里利用nums中的所有数字都独一无二这个条件,使用异或运算来对数组index及值进行运算,遍历完得出的结果就是丢失的数字。

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



好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:
LeetCode1-260题汇总,希望对你有点帮助!
LeetCode刷题实战261:以图判树
LeetCode刷题实战262:行程和用户LeetCode刷题实战263:丑数
LeetCode刷题实战264:丑数 IILeetCode刷题实战265:粉刷房子II
LeetCode刷题实战266:回文排列
LeetCode刷题实战267:回文排列II


浏览 7
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报