一道面试算法题

来源:互联网 发布:上海好的java培训机构 编辑:程序博客网 时间:2024/05/01 15:01
</pre><p></p>看到群里面有人发面试题<p></p><p></p><pre name="code" class="java">Best RegardsIrisQ1. 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: 25267566250558The 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++) { // 字母表长度为9if (mumber == 7) { // h 这个时候为7时停止,没考虑字符串str长度为8的限制System.out.println(a); // 打印结果// System.out.println("结束了");return;}double temp = mumber - i; //开始反向计算字符串与h = 37 * h + iif (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);}






0 0
原创粉丝点击