day81(2.9)——leetcode面试经典150

108. 将有序数组转换为二叉搜索树

108. 将有序数组转换为二叉搜索树

题目:

题解:

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    TreeNode conTree(int l, int r, int[] nums) { 
        if(l>r) {
            return null;
        }
        int mid = (l+r)/2;
        TreeNode node = new TreeNode(nums[mid]);
        node.left = conTree(l,mid-1,nums);
        node.right = conTree(mid+1,r,nums);
        return node;
    }
    
    public TreeNode sortedArrayToBST(int[] nums) {
        return conTree(0,nums.length-1,nums);
    }
}

148. 排序链表

148. 排序链表

题目:

题解:

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        if(head==null) {
            return head;
        }
        ListNode cur = head;
        List<Integer> list = new ArrayList<>();
        while(cur!=null) {
            list.add(cur.val);
            cur = cur.next;
        }
        list.sort(null);
        ListNode node = new ListNode();
        cur = node;
        for(int i=0;i<list.size();i++) {
            cur.val=list.get(i);
            if(i!=list.size()-1) {
                cur.next = new ListNode();
            }
            else {
                cur.next = null;
            }
            cur = cur.next;
        }
        return node;
    }
}
相关推荐
青少儿编程课堂16 分钟前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:Bellman-Ford与SPFA含负权最短路及负环检测全解析
c++·python·算法·bfs·信息学竞赛
文丑颜不良啊28 分钟前
LeetCode2061~2080题目解析
java·leetcode
j7~1 小时前
【C++ 八股文】(篇四)C++11 新特性
开发语言·c++·面试·c++11·八股文
octopus_c2 小时前
STL 之 string:auto 与范围 for、常用接口、模拟实现与深浅拷贝
开发语言·c++·算法
文丑颜不良啊13 小时前
LeetCode1941~1960题目解析
java·leetcode
nice_lcj52015 小时前
Java Lambda 表达式入门:怎么写、怎么用、常用方法有哪些
java·开发语言·后端·面试
老师我太想进步了202616 小时前
【数据结构-4】算法美学之顺序表
数据结构·算法
风影同志7832417 小时前
编码器是激活函数吗?—— 一个看起来很像、其实不是的类比
算法
UIU11417 小时前
P1481 魔族密码
c++·算法·动态规划
文丑颜不良啊17 小时前
LeetCode1961~1980题目解析
java·leetcode