算法题——Find the Duplicate Number(JAVA)

题目描述:
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Note:
You must not modify the array (assume the array is read only).
You must use only constant, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array, but it could be repeated more than once.

读题:
1.时间复杂度O(n^2)
2.空间复杂度O(1)
3.只有一个数字是重复的

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

解题思路:
1.使用堆排序排列数组
2.将每一个元素与下一个元素的值进行比较,若相等,则该值为重复的数字

提交代码:

public class Solution {
    int[] heap;
    int heapsize;
    public int findDuplicate(int[] nums) {
        int re = 1;
        this.heap = nums;    
        this.heapsize = heap.length;
        BuildMaxHeap();
        HeapSort();
        for(int i = 0; i < nums.length - 1; i++) {
            if (nums[i] == nums[i+1]) {
                re = nums[i];
                break;
            }
        }
        return re;
    }
    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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值