LeetCode OJ 268Missing Number

Posted xujian_2014

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode OJ 268Missing Number相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode.com/problems/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?

解题思路:题意为给定一个包含n个不重复的数的数组,从0,1,2...n,找出数组中遗漏的那个数。示例代码如下:

public class Solution

	public int missingNumber(int[] nums) 
	
		//首先对数组进行排序
		Arrays.sort(nums);
		int startData=nums[0];
		for(int i=1;i<nums.length;i++)
		
			//检查数组是否连续
			if((startData+1)==nums[i])
			
				startData=nums[i];
			
			else
			
				return startData+1;
			
		
		/**
		 * 如果数组是连续的
		 * 起始值不是0,则返回0,否则返回数组末尾数的下一个自然数
		 */
		if(startData==nums[nums.length-1])
		
			if(nums[0]>0)
				return 0;
			else
				return nums[nums.length-1]+1;
		
		return 0;
    


以上是关于LeetCode OJ 268Missing Number的主要内容,如果未能解决你的问题,请参考以下文章

&lt;LeetCode OJ&gt; 268. Missing Number

Leetcode-268 Missing Number

LeetCode:268. Missing Number

leetcode268 - Missing Number - easy

LeetCode 268. Missing Number

Leetcode 268: Missing Number