一道面試算法題

</pre><p></p>看到羣裏面有人發麪試題<p></p><p></p><pre name="code" class="java">Best Regards
Iris
Q1. 
Given a array of 10,000 random intergers, select the biggest 100 
numbers.
1) The order of the result numbers does not matter;
2) Take care about the algorithm performance and big O 

complexity.


Q2.
Find the string which has this hash: 25267566250558
The string has length 8.
Characters can be from: c,e,i,a,r,w,u,s,p
 
The hash function works like this:
hash(str):
    1. LETTERS = c, e, i, a, r, w, u, s, p
    2. h = 7
    3. for c in str:
        1. i = index of c in LETTERS
        2. h = 37 * h + i
    4. return h
 
Please send us the string you found, and the code you used to find 
it.
cueasa
--
收到請回復~謝謝 Iris
以回覆郵件爲準,否則視爲主動放棄面試機會 


第一題,主要是排序就不說了,第二到題我的做法是

	public static char[] k = {'c', 'e', 'i', 'a', 'r', 'w', 'u', 's', 'p'};
	public static void find(double mumber) {
		for (int i = 8; i>=0 ; i--) {
			if (mumber == 7) {   //h已經爲7了結束遞歸了
				System.out.println("結束了");
				return;
			}
			double temp = mumber - i;  //反過來求每一個h和字符下標
			if (temp % 37 == 0) {
//				System.out.println("下標爲" + i);
				System.out.print(k[i]);
				find(temp / 37);		//遞歸查找下一個字符
			}
		}
	}

	public static void main(String[] args) {
		double double1 = 25267566250558L;
		find(double1);
	}

這題有剛好只有一個結果,所以沒問題,我又想給它改良


改良版

public static char[] k = { 'c', 'e', 'i', 'a', 'r', 'w', 'u', 's', 'p' };

	public static void find(double mumber, char[] a,int j) {
		boolean hasResult = true;
		for (int i = 0; i <= 8; i++) { // 字母表長度爲9
			if (mumber == 7) { // h 這個時候爲7時停止,沒考慮字符串str長度爲8的限制
				System.out.println(a); // 打印結果
				// System.out.println("結束了");
				return;
			}
			double temp = mumber - i; //開始反向計算字符串與h = 37 * h + i
			if (temp % 37 == 0) {	//能整除
				a[j] = k[i];
				find(temp / 37, a,j+1);
			}
		}
	}
	
	public static void main(String[] args) {
		double double1 = 25267566250558L;
		find(double1, new char[9],0);
	}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章