Leetcode Note: Missing number

Source: Internet
Author: User

I. Title Description

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n , find the one and that's missing from the array.

For example,
Given nums = [0, 1, 3] return 2 .

Note:

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

Two. Topic analysis

The main idea is, given an 0, 1, 2, ..., n array of different numbers from which to select, find the n missing number in the array. And give a simple example.

The algorithm can satisfy the linear time complexity and constant space complexity of the problem.

Since the elements in the array are not equal and only one is missing, a simple idea is to 0 n get the missing number from the sum of the arithmetic progression before n and minus the accumulated elements of the array.

If you use bit arithmetic, this problem with singe number is a type, where the deformation is the first need to be 0, 1, 2, ..., n again into this array.

Three. Sample code

//arithmetic progression sumclassSolution { Public:intMissingnumber ( vector<int>& Nums) {intn = nums.size ();if(N <1)return 0;intCompletesum = n * (n +1) /2, Currsum =0; for(inti =0; I < n; ++i) Currsum + = Nums[i];returnCompletesum-currsum; }};
//bit operation  class  Solution {public : int  missingnumber (vector  <int  >  & nums) {int  ans = 0 ; for  (vector  <int ; :: Size_type i = 0 ; I < nums.size (); ++i) {ans ^= nums[i]; } for  (int  i = 0; I <= nums.size (); ++i) {ans ^= i; } return  ans; }};

Four. Summary

The conditions given in this topic are more lenient, such as the values are not duplicated. Directly using the arithmetic progression summation method can quickly find the missing number, only a few minutes to achieve, but no exercise value, you can try to solve the problem using an XOR operation.

Leetcode Note: Missing number

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.