zoukankan      html  css  js  c++  java
  • 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 should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

    思路:我的方法是根据nums数组的大小,先计算出如果没有数缺少时所有数的和,利用公式 n * (n + 1) / 2即可。但这样会有溢出的危险。

    看了discussion之后,被里面利用位运算的答案所深深震撼。

    其主要思路就是,如果现在的数组里有一个数缺失,那么我们将这些数进行异或运算,然后再异或一遍完整的数。

    那么没有缺失的数将会被异或两遍,而缺失的则只会被异或一遍。最后异或完的结果就是缺失的数字!

    1 class Solution {
    2 public:
    3     int missingNumber(vector<int>& nums) {
    4         int res = 0;
    5         for (int i = 0, n = nums.size(); i < n; i++)
    6             res ^= nums[i] ^ (i + 1);
    7         return res;
    8     }
    9 };
  • 相关阅读:
    访问修饰符的权限。
    字符编码
    3/11 作业
    3/10 作业
    作业 3/9
    流程控制之for循环
    Exception in createBlockOutputStream
    windows上传文件到 linux的hdfs
    win10 配置 hadoop-2.7.2
    hadoop 源码编译
  • 原文地址:https://www.cnblogs.com/fenshen371/p/4913740.html
Copyright © 2011-2022 走看看