一道面试算法题

</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);
	}






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