zoukankan      html  css  js  c++  java
  • 268. 丢失的数字 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.

    给定一个包含从0, 1, 2, ..., n, 选出的n个不同数字的数组,从中找出数组中缺失的那一个数。

    Note:
    Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

    注意:

    你的算法应该满足线性时间复杂度。你可以只使用常数空间复杂度完成此题吗?


    思路:等差数列前n项和 - 数组之和
    1. static public int MissingNumber(int[] nums) {
    2. if (nums.Length == 0) {
    3. return 0;
    4. }
    5. int max = 0;
    6. int min = Int32.MaxValue;
    7. int total = 0;
    8. foreach (int i in nums) {
    9. total += i;
    10. min = i < min ? i : min;
    11. max = i > max ? i : max;
    12. }
    13. int rest = max * (max + 1) / 2 - total;
    14. if (min == 0) {
    15. return (rest == 0) ? max + 1 : rest;
    16. } else {
    17. return min - 1;
    18. }
    19. }

    他山之石:

    从CPU指令所耗费的时钟周期来看,比加法更高效率的运算是异或(XOR)运算。本题的标签里有位运算,暗示本题可以用位运算的方法解决。

    异或运算的一个重要性质是,相同的数异或得0,不同的数异或不为0,且此性质可以推广到多个数异或的情形。本题的解法如下,首先将0到n这些数进行异或运算,然后对输入的数组进行异或运算,最后将两个结果进行异或运算,结果便是漏掉的数字,因为其他数字在两个数组中都是成对出现的,异或运算会得到0。


    1. class Solution {
    2. public:
    3. int missingNumber(vector<int>& nums) {
    4. int x = 0;
    5. for (int i = 0; i <= nums.size(); i++) x ^= i;
    6. for (auto n : nums) x ^= n;
    7. return x;
    8. }
    9. };





  • 相关阅读:
    关于 TIdHttp
    DCEF3 相关资料
    WPF RichTextBox 控件常用方法和属性
    Delphi Data Type to C# Data Type
    获取 CPU 序列号
    Visual Studio 调用 Delphi DLL 会退出的解决方案
    IDHttp的基本用法(转)
    TChromeTabs 优化改进
    java与json转换
    js charAt()方法
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/6968748b7935a65afc680d86e4e53505.html
Copyright © 2011-2022 走看看