[LeetCode]268. Missing Number

来源:互联网 发布:消毒餐具配送软件 编辑:程序博客网 时间:2024/06/15 02:26

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?


思路:所给数组中所有数的和,和应该的所有数的和的差,就是缺失的数


public class Solution {    public int missingNumber(int[] nums) {        int total=0;        for(int i=0;i<nums.length;i++){            total+=nums[i];        }        return (0+nums.length)*(nums.length+1)/2-total;            }}


0 0
原创粉丝点击