(FB) Excel Sheet, Remove Duplicates

比较简单,一次 AC. 这个代码不算是最简洁的,但是面试将近,我的代码风格开始向 “容易看懂 + 好交流 + 失误率低” 靠拢。。

26 - Z

52 - AZ

1000 - ALL

这里面的 'Z' 其实相当于 N 进制里面的 0;代表着 place holder.

可以看到填充顺序其实是从后往前,每一步取 % 26 的余数。只有 26 的倍数比较特殊,余数为 0 的时候,append Z 并且要减去 26,其他时候用 offset 就好了。

public class Solution {
    public String convertToTitle(int n) {
        if(n <= 0) return "";

        StringBuilder sb = new StringBuilder();
        while(n > 0){
            int digit = n % 26;

            if(digit == 0){
                sb.append('Z');
                n -= 26;
            } else {
                char chr = (char)('A' + digit - 1);
                sb.append(chr);
            }

            n = n / 26;

        }
        return sb.reverse().toString();
    }
}

掌握了这个特性之后,解码就变得非常容易了。。

public class Solution {
    public int titleToNumber(String s) {
        int num = 0;
        for(int i = 0; i < s.length(); i++){
            num *= 26;
            num += (int) s.charAt(i) - 'A' + 1;
        }
        return num;
    }
}

60秒 AC .. 这么水题我都有点不好意思了。。。

public class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        if(nums.length <= 2) return nums.length;

        int ptr = 2;
        for(int i = 2; i < nums.length; i++){
            if(nums[i] == nums[ptr - 1] && nums[i] == nums[ptr - 2]) continue;
            else nums[ptr++] = nums[i];
        }
        return ptr;
    }
}

也挺简单的,但是多了几个细节:

  • 这次是只要是 duplicate 就全跳过;

  • 因此看到一截重复的就全部跳过,但同时要注意不要假设一段重复的后面不会接着出现另外一段;所以处理完一段直接 continue;

  • dummy node 不能无脑连 head ,没准 head 里面的一个都不取,所以就建个 dummy 之后 next 先空着,自己一个一个加上去;

  • 从 dummy 出发的 cur 连完了之后,要记得循环结束时切断尾巴,因为我们在循环中只跳过,没切断,最后的收尾要自己做一下。

    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        while(head != null){
            if(head.next != null && head.val == head.next.val){
                int duplicateVal = head.val;
                while(head != null && head.val == duplicateVal) head = head.next;
    
                // Can't assume next value we see isn't duplicate as well;
                continue;
            }
    
            cur.next = head;
            cur = cur.next;
            head = head.next;
        }
        // Need to cut the tail
        cur.next = null;
    
        return dummy.next;
    }

Last updated