算法面试题

Posted ningff

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法面试题相关的知识,希望对你有一定的参考价值。

42. 接雨水

class Solution {
    public int trap(int[] height) {
        int size = height.length;
        int[] left = new int[size];
        int[] right = new int[size];
        for (int i = 1;i < size;i++){
            left[i] = Math.max(left[i - 1],height[i - 1]);
        }
        for (int i = size - 2;i >= 0;i--){
            right[i] = Math.max(right[i + 1],height[i + 1]);
        }
        int res = 0;
        for (int i = 1;i < size;i++){
            int min = Math.min(left[i],right[i]);
            if (min > height[i]){
                res += min - height[i];
            }
        }
        return res;
    }
}

 

445. 两数相加 II

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode p1 = reverseListNode(l1);
        ListNode p2 = reverseListNode(l2);
        int c = 0;
        ListNode dummy = new ListNode(0);
        ListNode p = dummy;
        while (p1 != null || p2 != null){
            int x = (p1 == null ? 0 : p1.val);
            int y = (p2 == null ? 0 : p2.val);
            int num = (x + y + c) %10;
            c = (x + y + c) /10;
            p.next = new ListNode(num);
            p = p.next;
            if (p1 != null){
                p1 = p1.next; 
            }
            if (p2 != null){
                p2 = p2.next;
            }
        }
        if (c > 0){
            p.next = new ListNode(c);
        }
        return reverseListNode(dummy.next);
    }
    public ListNode reverseListNode(ListNode head){
        if (head == null || head.next == null){
            return head;
        }
        ListNode pre = null;
        ListNode curr = head;
        while (curr != null){
            ListNode temp = curr.next;
            curr.next = pre;
            pre = curr;
            curr = temp;
        }
        return pre;
    }
}

 

以上是关于算法面试题的主要内容,如果未能解决你的问题,请参考以下文章

算法面试手撕代码高频题汇集

算法刷题范围建议 和 代码规范

算法刷题范围建议 和 代码规范

高频算法面试题_旋转字符串(完整的代码实现)

Java进阶之光!2021必看-Java高级面试题总结

深度学习/机器视觉/数字IC/FPGA/算法手撕代码目录总汇