LeetCode 268. Missing Number

来源:互联网 发布:开淘宝网店没有销量 编辑:程序博客网 时间:2024/05/04 14:02

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 这 n+1 个数中的 n 个,这 n 个数不重复,乱序的在数组中存放,求出数组中不包含的那个数字。

解法一:

数学方法:我们知道 0 ~ n 这 n+1 个数之和,减去数组各元素即得到最后的Missing Number

代码:

public class Solution {    public int missingNumber(int[] nums) {        int n = nums.length;        int result = n*(n + 1)/2;        for(int i = 0; i < n; i++){            result -= nums[i];        }        return result;            }}
解法二:

位运算:0 ~ n 这 n+1 个数异或所得的数 与 数组各元素异或所得的数 不同就在于 Missing Number,那么可以通过两个和的异或(XOR)获得

代码:

public class Solution {    public int missingNumber(int[] nums) {                int totalXOR = 1;        int numsXOR = nums[0];        for(int i = 1; i < nums.length; i++){            numsXOR = nums[i] ^ numsXOR;        }        for(int i = 2; i <= nums.length; i++){            totalXOR = i ^ totalXOR;        }        return numsXOR ^ totalXOR;                    }}
解法三:

将数组中的元素排序,遍历数组,索引值与当前元素值相等则继续,索引值和当前元素值不同,则返回;如果全部相同,则返回索引的下一个值。

[0,1,2,3,5]-->返回4;[0,1,2,3,4]-->返回5.

代码:

public class Solution {    public int missingNumber(int[] nums) {                Arrays.sort(nums);        int index;        for(index = 0; index < nums.length; index++){            if(index != nums[index]){                return index;            }        }        return index;    }}






0 0
原创粉丝点击