The Solution to Leetcode 268 Missing Number

来源:互联网 发布:报关软件 编辑:程序博客网 时间:2024/06/03 09:13

Question:

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.

思路:先将所给的数组进行从小到大的排序,然后判断数组元素的下标与它的值是否相等,若不相等,则就是遗失的那个元素。

Answer:

class Solution {public:    int missingNumber(vector<int>& nums) {        int i;        sort(nums.begin(),nums.end());        int n=nums.size();        for(i==0;i<n;i++)        {            if(nums[i]!=i)            {             return i;             break;            }        }            }};

Run code result:

Your input
[0,1 , 3] 
Your answer
2
Expected answer
2