zoukankan      html  css  js  c++  java
  • 【LeetCode OJ 268】Missing 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(6. Z 字形变换)
    二分查找
    线性查找
    平安寿险Java面试-社招-四面(2019/08)
    希尔排序
    中移物联网Java面试-社招-三面(2019/07)
    插入排序
    选择排序
    冒泡排序
    八皇后问题
  • 原文地址:https://www.cnblogs.com/jzssuanfa/p/7140540.html
Copyright © 2011-2022 走看看