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.

    Note:

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

     

    Solution 1: sum(0,1,...,n)-sum(array)=missing number 

    1 class Solution {
    2 public:
    3     int missingNumber(vector<int>& nums) {
    4         long long sum1=0,sum2=0;
    5         for (int num:nums) sum1+=num;
    6         for (int i=0;i<nums.size()+1;i++) sum2+=i;
    7         return sum2-sum1;
    8     }
    9 };

     Solution 2: Use the bit manipulation XOR(exclusive or). XOR has the properties: A^A=0,A^0=A. XOR all the (2n+1) numbers, the result is the missing number.

     1 class Solution {
     2 public:
     3     int missingNumber(vector<int>& nums) {
     4         int res=0,n=nums.size();
     5         for (int i=0;i<n;i++){
     6             res^=(i+1)^nums[i];
     7         }
     8         return res;
     9     }
    10 };
  • 相关阅读:
    关于代码片段
    感谢visual studio(git插件)救我一命
    SRX一些配置命令
    .NET Core Policy和Claim
    .NET Core Identity 用户管理和策略
    .NET Core基础配置、注册服务、中间件、ViewComponent、DbContext
    table非常细边框
    js数字转大写金额
    蓝牙开发
    Laravel artisan 命令
  • 原文地址:https://www.cnblogs.com/anghostcici/p/6669188.html
Copyright © 2011-2022 走看看