LeetCode刷题【Array】 Missing Number

来源:互联网 发布:数据分析ppt分享 编辑:程序博客网 时间:2024/06/06 11:47

题目:

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?

解决方法一Runtime: 1 ms

public class Solution {    public int missingNumber(int[] nums) {        if(null==nums) return -1;        int n=nums.length;        int a=0;        int b=0;        boolean flag=false;        a=(0+n)*(n+1)/2;        for(int i=0;i<n;i++){            b+=nums[i];            if(nums[i]==0) flag=true;        }        if(flag==false) return 0;        else return a-b;    }}

解决方法二Runtime: 1 ms 和方法一的思路基本一致,在循环遍历数组时,利用下标求和并减去数组值和便可得到缺失的数;

public class Solution {    public int missingNumber(int[] nums) {        if(null==nums) return -1;        int sum=nums.length;        for(int i=0;i<nums.length;i++){            sum+=i-nums[i];        }        return sum;    }}
解决方法三: 利用XOR运算的性质,a^a^b=b;则对数组中的元素与下标XOR运算,最后余下的为缺失的数 Runtime: 2 ms

public class Solution {    public int missingNumber(int[] nums) {        if(null==nums) return -1;        int m=nums.length;        for(int i=0;i<nums.length;i++){            m=m^i^nums[i];        }        return m;    }}

参考:

【1】https://leetcode.com/




0 0