leetcod--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.

解题思路:先求一遍不缺少情况下数组的和,然后减去缺少情况下数组的元素,差值就是缺少的元素。

#include <iostream>
#include<vector>
using namespace std;

int missingNumber(vector<int>& nums)
{
    int n=nums.size();
    cout<<n<<endl;
    int sum=(0+n)*(n+1)/2;
    for(int i=0; i<n; i++)  sum-=nums[i];
    return sum;
}
int main()
{
    vector<int> num;
    num.push_back(0);
    num.push_back(1);
    num.push_back(2);
    num.push_back(4);
    int s=missingNumber(num);
    cout<<s<<endl;

}

拓展:如果要找到缺失的2个数呢?

package leedcode;

import java.math.*;
import java.util.ArrayList;
import java.util.Arrays;

public class test {

    public static ArrayList missingNumber(int[] nums) {

        ArrayList List = new ArrayList();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != i)
                List.add(i);
        }
        return List;
    }

    // 主方法
    public static void main(String[] args) {
        int[] s = { 0, 2, 4, 5, 6 };
        ArrayList r = missingNumber(s);
        System.out.println(r.get(1));
    }
}

不太好的一点就是开辟了新的空间。。。。。。。。。。

你可能感兴趣的:(LeetCode,missingnum)