ARTS-Week 1
每周至少做一个leetcode的算法题、阅读并点评至少一篇英文技术文章、学习至少一个技术技巧、分享一篇有观点和思考的文章。(也就是Algorithm、Review、Tip、Share简称ARTS),至少坚持一年。
Algorithm
Add Two Numbers
Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解法1
思路是遍历数组的每一个成员,用 target 减去当前成员得到一个值,然后在剩余数组中查找是否有该值。
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
int data = target - nums[i];
for (int j = i+1; j < nums.length; j++) {
if (nums[j] == data) {
return new int[] {i, j};
}
}
}
return null;
}
}
解法2
public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
Review
学习论文 Kafka: a Distributed Messaging System for Log Processing
最近项目中有用到 Kafka,对于它的功能和应用场景不是很清楚,于是学习了论文 Kafka: a Distributed Messaging System for Log Processing,对它有了个大致的了解。作者首先介绍了 Kafka 产生的背景,传统消息系统当初的设计主要用于离线收集和加载数据,不能满足当前高实时处理大数据的需求。接下来详细描述了 Kafka 的系统架构以及设计原则,主要有高效处理(简单存储、高效传递、节点无状态),分布式协助,可靠传输。并介绍了在如何在 LinkedIn 系统部署和应用 Kafka。在和 RabbitMQ,ActiveMQ 的对比试验中,Kafka 的生产者发布消息的性能和消费者的性能都要优于 RabbitMQ,ActiveMQ。最后作者给出了 Kafka 后续的演进方向。
Tip
Spring MVC + Log4j
在用 Spring MVC 开发 Web 应用时,学习了如何使用 Log4j 添加日志打印。
- 在 pox.xml 添加 Log4j的依赖
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
- 在 resources 目录下创建配置文件 log4j.properties,并对日志进行配置
# Root logger option log4j.rootLogger=DEBUG, stdout, file # Redirect log messages to console log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n # Redirect log messages to a log file log4j.appender.file=org.apache.log4j.RollingFileAppender #outputs to Tomcat home log4j.appender.file.File=${catalina.home}/logs/myapp.log log4j.appender.file.MaxFileSize=5MB log4j.appender.file.MaxBackupIndex=10 log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
- 在代码中添加日志记录
public class HomeController { private static final Logger logger = Logger.getLogger(HomeController.class); @RequestMapping(method = GET) public String home() { logger.debug("come to the home.jsp."); return "home"; } }
Share
作者列举了软件开发活动的不同场景,针对不同场景给出了是否更新依赖,重构代码,清理冗余代码的建议。 When and why to clean up your code: now, later, never