码迷,mamicode.com
首页 > 编程语言 > 详细

算法面试题

时间:2019-11-18 00:02:19      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:str   ber   试题   lis   ==   算法   head   strong   problem   

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;
    }
}

 

算法面试题

标签:str   ber   试题   lis   ==   算法   head   strong   problem   

原文地址:https://www.cnblogs.com/ningff/p/11879020.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!