一道易于扩展的编码面试题(java描述)
原题参考酷壳http://coolshell.cn/articles/3961.html。
1)找错,考察细心程度,较易:
int n = 20;String s = "";for(int i = 0; i < n; i--) { s += "-";}System.out.println(s);2)只能添加一个字符或者修改其中一个字符使得逻辑正确,考察脑子是否够灵活,较难:
两个答案:
//第一种解法:在for循环中给 i 加一个负号for(int i = 0; -i < n; i--)//第二种解法:在for循环中把 i-- 变成 n--for(int i = 0; i < n; n--)
第三种解法在java中编译不通过,因为for的判断条件需要是boolean类型。而c不一样,非0就是true。
//第三种解法:把for循环中的 < 变成 +for(int i = 0; i + n; i--)
3)字符串拼写效率的改进,考察对String类型的理解,难度一般:
int n = 20000;StringBuffer s = new StringBuffer();for(int i = 0; i < n; i++) { s.append("-");}System.out.println(s.toString());如果使用原题的s+="-"拼写,在我机子测试700毫秒,改进后10毫秒。
4)对多线程环境的理解,考虑是否会使用同步、加锁等,难度一般:
单线程环境下可改进为:
StringBuffer->StringBuilder
5)对并发的理解,使用mapreduce思想提高效率,难度一般偏上:
int n = 10000000;// 1000w
1000w可拆分10组,每组100w。每组使用一个线程来处理,最后把10个线程的结果进行汇总。
这是我写的一个实现,可供参考。以下实现可能会出现Exception in thread "main" java.lang.OutOfMemoryError: Java heap space,需要设置更大的堆,在vm参数中设置-Xmx100m。
public class Concurrency { public static void main(String[] args) { long start = System.currentTimeMillis(); int n = 10000000; int count = 10; int every = n / count; CountDownLatch done = new CountDownLatch(count); List<StringBuilder> resultList = new ArrayList<StringBuilder>(); for(int i = 0; i < count; i++) { StringBuilder s = new StringBuilder(); resultList.add(s); new Thread(new Concurrency().new Task(s, every, done)).start(); } try { // 等待所有线程完成 done.await(); } catch (InterruptedException e) { e.printStackTrace(); } // 结果 StringBuilder result = new StringBuilder(); for (StringBuilder s : resultList) { result.append(s); } System.out.println(result.length()); System.out.println(System.currentTimeMillis() - start); } class Task implements Runnable { private StringBuilder s; private int n; private CountDownLatch done; public Task(StringBuilder s, int n, CountDownLatch done) { this.s = s; this.n = n; this.done = done; } public void run() { for(int i = 0; i < n; i++) { s.append("-"); } // 完成后计数减一 done.countDown(); } }}