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 };
  • 相关阅读:
    前端错误知识提示积累
    插件介绍之一:常用插件
    css小技巧积累
    设置网页地址栏小图标
    SEO优化篇——meta用法
    获取客户端的cookie
    come on,make a date progress bar together!
    教教你不用table制作出表格
    js实现快捷键绑定按钮点击事件
    Sublime Text3常用快捷键
  • 原文地址:https://www.cnblogs.com/anghostcici/p/6669188.html
Copyright © 2011-2022 走看看