腾讯面试题:
给你 10 分钟时间,根据上排给出十个数,在其下排填出对应的十个数,
要求下排每个数都是先前上排那十个数在下排出现的次数。
上排的十个数如下:
数值: 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 次....
给你 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 次....
以此类推..
package shuai.study.frequency;
/**
* @author shengshu
*
*/
public class NumberFrequency {
private final int len = 10;
private int[] numberArray = null;
private int[] frequencyArray = null;
public NumberFrequency() {
numberArray = new int[len];
frequencyArray = new int[len];
}
// Initialize numberArray
public void initNumberArray() {
for (int i = 0; i < len; i++) {
numberArray[i] = i;
}
}
// Get final frequencyArray
public int[] getFrequencyArray() {
while (isSetFrequencyArray(numberArray)) {
isSetFrequencyArray(numberArray);
}
return frequencyArray;
}
// Whether set frequencyArray according to judging 'frequencyArray[i] != frequency'
public boolean isSetFrequencyArray(int[] numberArray) {
boolean setNextFrequencyFlag = false;
for (int i = 0; i < len; i++) {
int frequency = getFrequency(numberArray[i]);
if (frequencyArray[i] != frequency) {
frequencyArray[i] = frequency;
setNextFrequencyFlag = true;
}
}
return setNextFrequencyFlag;
}
// Get numberArray's element(number) frequency
public int getFrequency(int number) {
int frequency = 0;
for (int i = 0; i < len; i++) {
if (frequencyArray[i] == number) {
frequency++;
}
}
return frequency;
}
// Print array
public void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + "\t");
}
}
// Main thread
public static void main(String[] args) {
NumberFrequency numberFrequency = new NumberFrequency();
numberFrequency.initNumberArray();
int[] frequencyArray = numberFrequency.getFrequencyArray();
numberFrequency.printArray(frequencyArray);
}
}