1046. 最后一块石头的重量

void swap(int *array, int a, int b)
{
    int tmp = array[a];
    array[a] = array[b];
    array[b] = tmp;
}
void heapfy(int *array, int n, int i)
{
    if(i >= n) {
        return ;
    }
    int c1 = i * 2 + 1;
    int c2 = i * 2 + 2;
    int max = i;
   // printf("%d\n",n);
   // printf("max=%d,i=%d,c1=%d,c2=%d\n",max,i,c1,c2);
   //  printf("%d\n",n);
    if(c1 < n && array[c1] > array[max]) {
       // printf("%d,%d\n",array[c1],array[max]);
        max = c1;
    }
    if(c2 < n && array[c2] > array[max]) {
      //  printf("%d,%d\n",array[c2],array[max]);
        max = c2;
    }
    //printf("%d,%d,%d\n",array[c1],array[c2],array[max]);
   // printf("max=%d,i=%d\n",max,i);
    if(max != i) {
        swap(array, max, i);
        heapfy(array, n, max);
    }
}
void build_heapy(int *array, int n)
{
    int last = n-1;
    for(int i = (last-1)/2; i>=0; i--) {
        heapfy(array, n, i);
    }
}
void sort_heap(int *array, int n)
{
    build_heapy(array, n);
    // for(int i = n-1; i >=0; i--) {
    //     swap(array, i, 0);
    //     heapfy(array, i, 0);
    // }
}
int heap_pop(int *array, int n)
{
    int tmp = array[0];
    swap(array, n-1, 0);
    heapfy(array,n-1, 0);
    return tmp;
}
void heap_push(int *array, int n, int value)
{
    array[n-1] = value;
    build_heapy(array, n);
}
int lastStoneWeight(int* stones, int stonesSize){
    build_heapy(stones, stonesSize);
    int totolnum = stonesSize;
    if(stonesSize == 1) {
        return stones[0];
    }
    for(int i = 0; i < totolnum; i++) {
        printf("%d\n",stones[i]);
    }
   
  
   
     while(1) {
        int first = heap_pop(stones, totolnum);
        totolnum--;
        int second = heap_pop(stones,totolnum);
        totolnum--;
        printf("(%d,%d, totolnum=%d)",first, second, totolnum);
        if(first != second) {
            int value = first-second;
            totolnum++;
            heap_push(stones, totolnum, value);
        }
        if(totolnum == 0) {
            return 0;
        }
        if(totolnum == 1) {
            return stones[0];
        }
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值