313. 超级丑数 Super Ugly Number

题目 <https://leetcode-cn.com/problems/super-ugly-number/>

小堆

struct Heap{
    int *nums;
    int len;
    int cap;
};

struct Heap * heapCreate(int cap){
    struct Heap *heap = malloc(sizeof(struct Heap));
    heap->len = 0;
    heap->cap = cap;
    heap->nums = malloc(sizeof(int) * heap->cap);
    return heap;
}

void heapPush(struct Heap *heap,int val){
    int child = heap->len,parent;

    parent = (child-1)/2;
    while(child != 0 && val < heap->nums[parent]){
        heap->nums[child] = heap->nums[parent];
        child = parent;

        parent = (child-1)/2;
    }
    heap->nums[child] = val;
    heap->len++;
}


int heapPop(struct Heap *heap){
    int return_val = heap->nums[0];
    int val = heap->nums[heap->len-1];
    heap->len--;


    int parent = 0,child;
    child = parent*2+1;
    if(child+1 < heap->len && heap->nums[child+1] < heap->nums[child])
        child++;
    while(child<heap->len && val>heap->nums[child]){//注意是判断child
        heap->nums[parent] = heap->nums[child];
        parent = child;
        child = parent*2+1;
        if(child+1 < heap->len && heap->nums[child+1] < heap->nums[child])
            child++;
    }
    heap->nums[parent] = val;

    return return_val;
}

void heapFree(struct Heap *heap){
    free(heap->nums);
    free(heap);
}

int nthSuperUglyNumber(int n, int* primes, int primesSize){
    struct Heap * heap = heapCreate(n * primesSize);
    heapPush(heap,1);
    int i,j;
    long long k;
    for(i=1;i<n;i++){
        for(j=0;j<primesSize;j++){
            k = heap->nums[0];
            k *= primes[j];
            if(k <= INT_MAX)
                heapPush(heap,k);
        }
        k = heap->nums[0];
        while(k == heap->nums[0])
            heapPop(heap);
    }
    k = heap->nums[0];
    heapFree(heap);
    return k;
}

猜你喜欢

转载自blog.csdn.net/ZRXSLYG/article/details/112597495