leetCode No.268 Missing Number

来源:互联网 发布:淘宝三大苹果店 编辑:程序博客网 时间:2024/06/03 06:05

题目

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)
原题

0 0