arts week02

arts

Posted by Woncz on July 24, 2019

Algorithm

LeetCode算法题

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.

Java 程序实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null) {
            throw new IllegalArgumentException("illegal argument");
        }
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        
        // head
        int low = 0;
        int t = l1.val + l2.val;
        if (t > 9) {
            low = 1;
            t -= 10;
        }
        ListNode head = new ListNode(t);
        
        ListNode first = l1.next;
        ListNode second = l2.next;
        
        ListNode n = head;
        
        while (first != null || second != null || low == 1) {
            int x = first == null ? 0 : first.val;
            int y = second == null ? 0 : second.val;
            int total = x + y + low;
            // reset
            low = 0;
            if (total <= 9) {
                n.next = new ListNode(total);
            } else {
                n.next = new ListNode(total - 10);
                low = 1;
            }
            
            // forward
            first = first == null ? null : first.next;
            second = second == null ? null : second.next;
            n = n.next;
        }
        
        return head;
    }
}

Review

How to do distributed locking

详细介绍了分布式锁使用场景,Redis提供的Redlock分布式锁实现的鸡肋之处,代价大,要求高(时延),结论是一般场景用单节点的Redis锁,特殊场景基于zookeeper使用分布式锁。

Tip

错误越早发现,代价越小,如果从模型设计上就有问题,后续的实现基本就是补丁套补丁,丑陋不堪,费时耗力效果差,作为架构师,其设计能力至关重要。

Share

信息过载