給定一個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=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); }