leetCode No.268 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.

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

标签:Array、Math、Bit Manipulation
相似问题:(H) First Missing Positive,(E) Single Number,(H) Find the Duplicate Number

题意

给定一个整数n和一个数组,数组元素为1,2,3,4…n丢掉一个,找到丢掉的元素。

解题思路

根据长度n求得差值为1的等差数列的和,即为0到n所有数的和。再循环数组,用和减去数组中的元素即可得到缺失的元素。

代码

public class Solution {
    public int missingNumber(int[] nums) {
        int a = nums[0];
        int index = 0;
        for (int i = 0;i < nums.length;i++) {
            if (nums[i] == a + i) {
                if (i == nums.length - 1) {
                    index = nums[i] + 1;
                }
            } else {
                index = a + i;
                break;
            }
        }
        return index;
    }
}

相关链接

源代码(github)
原题

你可能感兴趣的:(LeetCode)