zoukankan      html  css  js  c++  java
  • leetcode 108 和leetcode 109 II

    //感想:没啥上篇写完了

    //思路:对于这道题109来说,就是数组变成了链表,其他没有变,我觉得非常不解,因为我想到的依旧是找中点,用快慢指针来找,

    找到以后将链表分成两半,继续递归的去找,我就觉得这不是白费力气吗?用数组不好吗?非这么麻烦,关键去中点每次都要去遍历一遍链表,毕竟是个链表,查找起来就是慢啊,难道非要为了炫技而将效率降低吗?我还是算了吧。

    我就是将整个链表遍历一遍放进数组中,然后跟上一题没啥区别了。

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 /**
    10  * Definition for a binary tree node.
    11  * public class TreeNode {
    12  *     int val;
    13  *     TreeNode left;
    14  *     TreeNode right;
    15  *     TreeNode(int x) { val = x; }
    16  * }
    17  */
    18 class Solution {
    19     public TreeNode sortedListToBST(ListNode head) {
    20         if(head==null)
    21             return null;
    22         ArrayList<Integer> list=new ArrayList<Integer>();
    23         ListNode p=head;
    24         while(p!=null)
    25         {
    26             list.add(p.val);
    27             p=p.next;
    28         }
    29         return helper(list,0,list.size()-1);
    30     }
    31     public TreeNode helper(ArrayList<Integer> list,int l,int r)
    32     {
    33         if(l>r)
    34             return null;
    35         int mid=l+(r-l)/2;
    36         TreeNode root=new TreeNode(list.get(mid));
    37         root.left=helper(list,l,mid-1);
    38         root.right=helper(list,mid+1,r);
    39         return root;
    40     }
    41 }
  • 相关阅读:
    Amazon后台登陆以及跟卖
    python图像识别--验证码
    python selenium下载电子书
    Amazon后台模拟登陆
    python简单粗暴多进程之concurrent.futures
    SmartDo数据挖掘思路
    python3倒叙字符串
    Effective C++ —— 构造/析构/赋值运算(二)
    Effective C++ —— 让自己习惯C++(一)
    cocos2dx-3.x物理引擎Box2D介绍
  • 原文地址:https://www.cnblogs.com/cold-windy/p/11779271.html
Copyright © 2011-2022 走看看