一道易于扩展的编码面试题(java描述)

原题参考酷壳[url]http://coolshell.cn/articles/3961.html[/url]。
[b]1)找错,考察细心程度,较易:[/b]
int n = 20;
String s = "";
for(int i = 0; i < n; i--) {
s += "-";
}
System.out.println(s);


[b]2)只能添加一个字符或者修改其中一个字符使得逻辑正确,考察脑子是否够灵活,较难:[/b]
两个答案:
//第一种解法:在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--)


[b]3)字符串拼写效率的改进,考察对String类型的理解,难度一般:[/b]
int n = 20000;
StringBuffer s = new StringBuffer();
for(int i = 0; i < n; i++) {
s.append("-");
}
System.out.println(s.toString());

如果使用原题的s+="-"拼写,在我机子测试700毫秒,改进后10毫秒。

[b]4)对多线程环境的理解,考虑是否会使用同步、加锁等,难度一般:[/b]
单线程环境下可改进为:
StringBuffer->StringBuilder


[b]5)对并发的理解,使用mapreduce思想提高效率,难度一般偏上:[/b]
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();
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值