Algorithm
LeetCode-229. Majority Element II
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. Note: The algorithm should run in linear time and in O(1) space.
[leetcode.com/problems/ma…](229. Majority Element II)
解答: 设置两个计数器,在遍历数组的时候,如果是2个计数器中的一个,则该计数器加1,否则全减1。
class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> result = new ArrayList<>();
int num1,num2,count1,count2;
num1 = -1;
num2 = -1;
count1 = 0;
count2 = 0;
for (int i=0; i< nums.length; i++) {
if (num1 == nums[i]) {
count1 ++;
continue;
}
if (num2 == nums[i]) {
count2 ++;
continue;
}
if (count1 == 0) {
num1 = nums[i];
count1++;
continue;
}
if (count2 == 0) {
num2 = nums[i];
count2++;
continue;
}
count1--;
count2--;
}
// check
count1 = 0;
count2 = 0;
for (int i=0; i<nums.length; i++) {
if (num1 == nums[i]) {
count1 ++;
continue;
}
if (num2 == nums[i]) {
count2 ++;
continue;
}
}
if (count1 > nums.length / 3) {
result.add(num1);
}
if (count2 > nums.length / 3) {
result.add(num2);
}
return result;
}
}
Review
Immutable empty collections and iterators
[www.javaworld.com/article/310…](Immutable empty collections and iterators)
主要是讲为什么Collections里面会有很多empty方法,会返回一个不可修改的空list。主要原因是为了代码写的更优雅,防止npe。
Tip
排查客户端请求到服务器问题时候如何复现问题
charles里面可以通过copy curl request的方式,让别人把复现的请求发来。不过考虑到有些请求是一次性的,最好是能让发现问题的同学直接用charles抓包,然后导出个session发过来,这样可以先通过请求参数格式和结果码结合代码排查下。
Share
关系型数据库是咋实现的
[coding-geek.com/how-databas…](How does a relational database work)
作为一个后端开发,一直用mysql开发,大部分db打交道都是crud。再有就是研究研究各种orm框架咋用,分库分表咋实现。对db了解仅限于索引实现,事务隔离级别了。最近开始琢磨着mysql主键和索引的实现细节,各种链接看过去,发现了这个文章,只能收藏推荐慢慢读,干货满满。