傳是騰訊的一道面試題,出的很有意思。題目如下:
給你10分鐘時間,根據上排給出十個數,在其下排填出對應的十個數要求下排每個數都是先前上排那十個數在下排出現的次數。上排的十個數如下:
【0,1,2,3,4,5,6,7,8,9】
舉一個例子,
數值: 0,1,2,3,4,5,6,7,8,9
分配: 6,2,1,0,0,0,1,0,0,0
0在下排出現了6次,1在下排出現了2次,
2在下排出現了1次,3在下排出現了0次….
以此類推..
此題目妙在乍一看很簡單,但是在實現過程中,發現結果需要動態規劃,重新檢查計算,直到所有值都是正確的,答案是在處理結果中動態獲得。
解題思路:
1、計算各個數據出現次數,用一個數組存儲。
2、檢測數據數組是否正確。
3、如果有位置不正確就重新計算。
4、如果都正確就輸出結果。
代碼如下:
package com.applee.exam1;
public class program2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int inputs[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int size = inputs.length;
int outputs[] = new int [size];
while(true){
boolean bBreak = true;
for(int i = 0; i < inputs.length; i++){
int times = 0;
for(int n = 0; n < outputs.length; n++){
if(inputs[i] == outputs[n])
times++;
}
if(outputs[i] != times){ //invalidate
int count = 0;
for(int n = 0; n < outputs.length; n++){ //count
if(inputs[i] == outputs[n])
count++;
}
outputs[i] = count;
bBreak = false;
}
}
if(bBreak)
break;
}
StringBuilder sInput = new StringBuilder();
sInput.append("數值:");
sInput.append(inputs[0]);
for(int i = 1; i < size; i++){
sInput.append(",");
sInput.append(inputs[i]);
}
System.out.println(sInput.toString());
StringBuilder sOutput = new StringBuilder();
sOutput.append("分配:");
sOutput.append(outputs[0]);
for(int i = 1; i < size; i++){
sOutput.append(",");
sOutput.append(outputs[i]);
}
System.out.println(sOutput.toString());
}
}
輸出結果: