【LeetCode】268. Missing Number

来源:互联网 发布:管家婆网络远程软件 编辑:程序博客网 时间:2024/06/05 16:31

问题描述

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?

解决方法

给定一个数组,数组中的元素取自0~n,而且元素各不相同,找到数组中缺失的那个元素。
例如:一个数组中有三个元素0,1,3,那么这个数组实际上是从0~3中取的数,缺失的那个数字就是2。

注意:
1. 需要线性的时间复杂度;
2. 数组中的元素不一定是有序的,0 1 3的顺序也可以是 3 1 0,这样的数组的输出结果是一样的。

class Solution{    public static int missingNumber(int[] nums)    {//        //1.XOR//        int miss = 0;//        for(int i=0; i<nums.length; i++)//        {//            miss ^= (i+1);//相当于将0 - nums.length+1逐个异或//            miss ^= nums[i];//nums逐个异或//        }//        return miss;//        //2.SUM//        int n = nums.length;//        int sum = n * (n + 1) / 2;//等差求和//        for(int i:nums)//        {//            sum -= i;//        }//        return sum;        //3.Binary Search        Arrays.sort(nums);        int n = nums.length;        int mid = 0;        int left=0,right=nums.length;        while(left<right)        {            mid = (left + right) / 2;            if(nums[mid] > mid)                right = mid;            else                left = mid+1;        }        return left;    }}
原创粉丝点击