Leetcode Note: Missing Number

Source: Internet
Author: User

Leetcode Note: Missing Number

I. Description

Given an array containing n distinct numbers taken from0, 1, 2, ..., n, Find the one that is missing from the array.

For example,
Givennums = [0, 1, 3]Return2.

Note:

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

Ii. Question Analysis

The general idea is to give0, 1, 2, ..., n, SelectednTo find the missing number in the array. A simple example is provided.

The question requires that the algorithm can meet the linear time complexity and constant space complexity.

Because the elements in the array are not equal and only one element is missing, a simple idea is to find0TonBeforenAnd subtract the sum of the elements in the array to get the missing number.

If bitwise operations are used, this question is of the same type as the singe number. The first step to deformation is to convert 0, 1, 2 ,..., N is added to this array again.

Iii. Sample Code

// Class Solution for the sum of the arithmetic difference series {public: int missingNumber (vector
  
   
& Nums) {int n = nums. size (); if (n <1) return 0; int completeSum = n * (n + 1)/2, currSum = 0; for (int I = 0; I <n; ++ I) currSum + = nums [I]; return completeSum-currSum ;}};
  
// Bitwise operation class Solution {public: int missingNumber (vector
  
   
& Nums) {int ans = 0; for (vector
   
    
: Size_type I = 0; I <nums. size (); ++ I) {ans ^ = nums [I];} for (int I = 0; I <= nums. size (); ++ I) {ans ^ = I;} return ans ;}};
   
  

Iv. Summary

The conditions given for this question are relatively loose. For example, the values are not repeated. You can use the sum method of the equals difference series to quickly find the missing number, which can be achieved in just a few minutes, but there is no practical value. You can try the exclusive or operation to solve this problem.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.