算法题——Missing Number(JAVA)

题目描述:
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?

读题:
1.时间复杂度O(n)
2.空间复杂度O(1)

知识储备:
堆排序同时满足时间和空间复杂度要求。
堆是一棵完全二叉树。使用最大堆,最大堆的最大元素一定在第0位置,其操作内容如下:对于每个节点i,我们考察他与子节点的大小,如果他比某个子节点小,则将他与子节点中最大的那个互换位置,然后在相应的子节点位置重复操作,直到到达堆的叶子节点或者考察的位置比子节点的值都要大为止。
构建好堆之后,交换0位置元素与顶,将heapsize减1,然后再在根节点出调用最大堆过程将新的堆重新最大堆化。依次循环,我们每次都能将现有堆中最大的元素放到堆末尾。最后就完成了整个排序过程。堆排序为原位排序(空间小), 且最坏运行时间是O(nlgn),是渐进最优的比较排序算法。

解题思路:
1.使用堆排序排列数组
2.从第二个元素开始与上一个元素的值进行比较,若相差1,则往下,直到某一元素与上一个元素的值相差2为止
3.注意当缺少的是位于两端的边界值
4.注意当数组只有一个元素时

提交代码:

public class Solution {
    int[] heap;
    int heapsize;
    public int missingNumber(int[] nums) {
        this.heap = nums;    
        this.heapsize = heap.length;
        if (nums.length == 1 && nums[0] == 0) {
            return 1;
        }
        if (nums.length == 1 && nums[0] == 1) {
            return 0;
        }
        BuildMaxHeap();
        HeapSort();
        int re = nums[heap.length-1] + 1;
        for(int i = 1; i < nums.length; i++) {
            if (nums[i] != nums[i-1] + 1) {
                re = nums[i] - 1;
                break;
            }
        }
        if (nums[0] == 0)
            return re;
        else
            return 0;
    }
    public void BuildMaxHeap() {
        for (int i = heapsize / 2 - 1; i >= 0; i--) {
            Maxify(i);
        }
    }
    public void Maxify(int i) {
        int l = Left(i);
        int r = Right(i);
        int largest;
        if (l < heapsize && heap[l] > heap[i])
            largest = l;
        else
            largest = i;
        if (r < heapsize && heap[r] > heap[largest])
            largest = r;
        if (largest == i || largest >= heapsize)
            return;
        int tmp = heap[i];
        heap[i] = heap[largest];
        heap[largest] = tmp;
        Maxify(largest);
    }
    public void HeapSort() {
        for (int i = 0; i < heap.length; i++) {
            int tmp = heap[0];
            heap[0] = heap[heapsize-1];
            heap[heapsize-1] = tmp;
            heapsize--;
            Maxify(0);
        }
    }
    private int Parent(int i) {
        return (i-1)/2;
    }
    private int Left(int i) {
        return 2*(i+1)-1;
    }
    private int Right(int i) {
        return 2*(i+1);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值