Algorithm
LeetCode 的第一题,比较简单。就是给一个数组,一个目标结果,返回数组中两个相加和为目标数的索引。
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].
因为没有做过算法题,所以刚开始的思路就是跟简单排序一样,拿出第一个数,然后轮询后面的数,并相加,看它们的和是否等于目标数,不等于就拿出第二个数往后,等于就返回索引。
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i+1;j < nums.length; j++) {
if (nums[i] + nums[j] == target) return new int[]{i,j};
}
}
throw new IllegalArgumentException("No tow sum solution");
}
这个的时间复杂度是: $O(1)$
空间复杂度就是:$O(n^2)$,如果是最后两个才匹配,那有点费时。
下面这个是官网solution 里面的解答,豁然开朗啊。轮询数组,然后看hashmap里面有没有目标数减去当前数的存在,没有就丢进去继续,有就返回。
public int[] twoSum_hashtable(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) return new int[]{map.get(complement),i};
//if not, put in to the map
map.put(nums[i],i);
}
throw new IllegalArgumentException("No tow sum solution");
}
测试
public class TwoSumTest {
TwoSum solution = new TwoSum();
@Test
public void twoSum() {
int[] arr = new int[]{3,7,9,22};
int target = 12;
assertEquals(Arrays.toString(new int[]{0,2}), Arrays.toString(solution.twoSum(arr,target)));
assertEquals(Arrays.toString(new int[]{0,2}), Arrays.toString(solution.twoSum_hashtable(arr,target)));
}
}
Review
How I learned to stop worrying and love the stress
stress is a part of our everyday lives
这句话跟《少有人走的路》的开篇差不多
Life is difficult. 都是在说其实人生不如意事十之八九。 我们要以一种积极健康的心态去面对我们每天所面对的压力,痛苦等。压力痛苦本身就在那里,如果你积极面对,会轻松很多,如果你更加消极,那么文中说到,这种影响可就更加的深远,影响心理健康,影响身体健康等。 文中提了四点建议:
- Reframe stress as an indicator that you care
- Take action to prevent paralyzing fear
- Focus on what you can change; forget what you can’t
- Surround yourself with positive people
现在人压力都越来越大了,程序员的压力也大。当然我其实感觉程序员其实已经算好了,一个智力工作者,而且这个工作让你不断的学习和适应,工资相较也高。
每个人都有每个人的忧愁与烦恼。我们要做的就是面对他们,然后分析他们因何产生,一定是因为自己某方面的不足所导致的。
王小波不是说过么:
人的一切痛苦,本质上都是对自己无能的愤怒。
所以,我们要补足自己的不足!
加油吧,骚年!
Tip
由于看到很多伙伴用的是github page,我自己一直想要去建站,然后建立自己的博客,可是弄来弄去太麻烦,而且没有那么多的时间去写。 而现在看到可以直接用github page来打造自己的博客,你不需要另外的数据库,不需要后台,因为所以的都是从github的仓库中读取的。 当然,这也是限制
GitHub Pages is a static site hosting service and doesn’t support server-side code such as, PHP, Ruby, or Python.
这是GitHub官方说明。
详细的操作步骤可以见README.md.
这也算这周折腾一晚上折腾出来的一个小成果了吧。
Share
Implementing AOP With Spring Boot and AspectJ
这周我想把自己的一个项目代码重构一下,就想到了用切面,这个里面详细的讲述了每个annotation 的意思,讲了切面里面一些晦涩的专有词汇。
当然啦,最官方的文档也是要推荐一下的。
Aspect Oriented Programming with Spring
但是这个文档内容太多,还是以查阅为主的。