给定一个N位数,比如12345,从里面去掉k个数字。得到一个N-k位的数。比如去掉2,4,得到135,去掉1,5。得到234。设计算法。求出全部得到的N-k位数里面最小的那一个。
写的代码例如以下,思路是通过堆排序得到N位数里边最大的前K个数,然后依照原数字的顺序去除得到的最大的K个数。
感觉写的非常乱,可能还有些小问题,鲁棒性应该非常差,努力锻炼。。努力提高。
typedef unsigned int uint; //Heap adjust function void HeapAdjust(uint *value, uint start, uint end) { for( int i=start; 2*i<=end; ) { uint index = 2*i; if(index+1<=end && value[index+1] > value[index]) index +=1; if(value[index] > value[i]) { uint temp = value[i]; value[i] = value[index]; value[index] = temp; } i = index; } } //Heap creation function void CreateHeap(uint *value, uint start, uint end) { uint middle = (start+end)/2; for( uint i = middle;i>=start;i--) { HeapAdjust(value, i, end); } } //Kick K numbers from N uint KickK(uint N, uint K) { if(N>4294967295) return 0; uint i,tempN=N; uint length=0; uint value[10],outValue[10]; bool flag; i = 1; //get the numbers of N while(tempN != 0) { value[i]=tempN%10; outValue[i]=value[i]; tempN=tempN/10; i++; } length = i-1; //check the condition if(K >= length) return 0; //Get the K biggest numbers, and store then in the last K positions in array value CreateHeap(value,1,length); for(i=0;i<K;i++) { uint temp = value[length-i]; value[length-i] = value[1]; value[1] = temp; CreateHeap(value,1,length-i-1); } //output the remained numbers ,despite the K biggest numbers for(i=length;i>=1;i--) { flag = true; for(uint j=length+1-K;j<=length; j++) { if(outValue[i] == value[j]) flag = false; } if(flag) printf("%d", outValue[i]); } return 1; } int main() { uint N=61829; uint K=3; KickK(N,K); }