最近开始看耗子叔的《程序员练级攻略》,不是科班出身,底子薄,准备从头把基础打扎实。
Algorithm
leetcode——1、Two Sum
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].
Solution 1:自己思考的思路——通过两层循环遍历,相加与target进行条件判断,时间复杂度为O(n2),空间复杂度为O(1)。
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0;i < nums.length;i++){
for(int j = i + 1;j < nums.length;j++){
if(nums[i] + nums[j] == target){
return new int[]{i,j};
}
}
}
return null;
}
}
Solution 2:leetcode上的思路——循环遍历一遍数组,将数组数据存入hashmap中,在循环的过程中进行hashmap.containsKey()判断,因为containKey()时间复杂度为O(1),所以整体时间复杂度为O(n)。由于需要将全部数组数据存入hashmap中,所以空间复杂度为O(n)。该算法适用于数组较大,内存空间充足的情况。
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>(nums.length);
for (int i = 0; i < nums.length; i++) {
int value = target - nums[i];
if (map.containsKey(value)) {
return new int[]{map.get(value),i};
}
map.put(nums[i],i);
}
return null;
}
}
Review
在看完 The key to Accelerating your Coding Skills 后,有一些心得体会:
1、只要你还在写代码,就会有bug,重要的是培养解决bug的思维和能力,而不是仅限于解决完bug,因为bug是处理不完的。但是实际上很多时候,我们仅仅是在网上找到相关的答案,问题解决,就不再深入探究了。
2、要培养自己独立解决问题的能力,就必须走出舒适区。技术是持续变化的,只有不断了解新的技术,才能不被淘汰,前提就是走出舒适区,学习并了解新的技术。
3、学好数据结构和算法。重要的是思考的过程,而不是答案。以自己的思维去思考并去实现每一种常用的数据结构和算法。
Tips
问题:服务器上配置文件很多,怎么批量修改某一个内容?比如修改dubbo的注册地址,前提是各个服务需要修改的配置文件的名称是一致的。
解决:find、xargs和sed 联合使用,xargs可以通过管道来传递参数,sed主要用来进行替换、删除、添加等操作。
find -name ‘dubbo.properties’|xargs sed ‘s/127.0.0.1/localhost/g’
查找所有名称为dubbo.properties的配置文件,将127.0.01全部替换为localhost。
Share
最近遇到的多线程的问题,记录一下。对线程的一点理解