zoukankan      html  css  js  c++  java
  • Leetcode86.分隔链表

    题目连接:86.分隔链表

    思路:遍历一遍链表,将表中结点分为两类,一类是小于给定的x,另一类是大于等于x。输出结果时要考虑四种情况:输入的表头为空;没有小于x的节点;没有大于等于x的节点;既有小于x又有大于等于x的。

    代码:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode partition(ListNode head, int x) {
            if(head == null) return head;
            int len = 0, li = 0, mti = 0;
            for(ListNode p=head; p!=null; p=p.next) len ++;
            ListNode[] less = new ListNode[len];
            ListNode[] moreThen = new ListNode[len];
            for(ListNode p=head; p!=null; p=p.next){
                if(p.val < x){
                    if(li > 0) less[li-1].next = p;
                    less[li++] = p;
                }else{
                    if(mti > 0) moreThen[mti-1].next = p;
                    moreThen[mti++] = p;
                }
            }
            if(mti>0 && li>0){
                less[li-1].next = moreThen[0];
                moreThen[mti-1].next = null;
                return less[0];
            }
            if(li==0){
                return moreThen[0];
            }
            return less[0];
        }
    }
    

    执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
    内存消耗:37.3 MB, 在所有 Java 提交中击败了98.07%的用户

  • 相关阅读:
    访存模型
    Petri网
    Forward secrecy
    TensorFlow训练神经网络cost一直为0
    解决tensorflow在训练的时候权重是nan问题
    tf.argmax
    Keras教程
    z-score
    隐马尔可夫(HMM)、前/后向算法、Viterbi算法
    受限玻尔兹曼机基础教程
  • 原文地址:https://www.cnblogs.com/liuyongyu/p/14203731.html
Copyright © 2011-2022 走看看