閾捐〃--鍒嗛殧閾捐〃锛坙eetcode86

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了閾捐〃--鍒嗛殧閾捐〃锛坙eetcode86相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/%e9%93%be%e8%a1%a8' title='閾捐〃'>閾捐〃   after   int   鎸囬拡   鏂板缓   閬嶅巻   else   绌洪棿   str   

棰樿В

  • 涓嶇敤淇敼鍘熷閾捐〃锛堝仛棰樹笉瑕佸お姝绘澘锛屼笉涓€瀹氶潪瑕佸湪鍘熷閾捐〃涓婅繘琛屼慨鏀癸級
  • 鏂板缓涓や釜閾捐〃before鍜宎fter
  • 鍦ㄩ亶鍘嗗師濮嬮摼琛ㄧ殑杩囩▼涓紝灏忎簬x鐨勬彃鍏ュ埌before涓紝澶т簬x鐨勬彃鍏ュ埌after涓?/li>
public ListNode partition(ListNode head, int x) {
        ListNode beforeHead = new ListNode(-1);
        ListNode afterHead = new ListNode(-1);
        ListNode before = beforeHead;
        ListNode after = afterHead;
        
        while (head != null){
            if(head.val < x){
                before.next = head;
                before = before.next;
            }else {
                after.next = head;
                after = after.next;
            }
            head = head.next;
        }

        after.next = null;
        
        before.next = afterHead.next;
        
        return beforeHead.next;
    }

鏃堕棿澶嶆潅搴︼細O(N)锛孨涓洪摼琛ㄩ暱搴?/p>

绌洪棿澶嶆潅搴︼細O(1)锛岃繖涓増鏈殑浠g爜鏄病鏈夊垎閰嶆柊绌洪棿鐨勭増鏈紝鍙Щ鍔ㄤ簡鍘熸湁鐨勭粨鐐癸紝鍥犳娌℃湁浣跨敤浠讳綍棰濆绌洪棿銆?/p>

鍙﹀锛宎fter.next = null鏄緢鏈夊繀瑕佺殑锛屼笉鑳藉嚭鐜伴噹鎸囬拡


鎴戣嚜宸卞啓鐨勭瓟妗堟槸鏂板缓浜嗙粨鐐圭殑

public ListNode partition(ListNode head, int x) {
        ListNode beforeHead = new ListNode(-1);
        ListNode afterHead = new ListNode(-1);
        ListNode before = beforeHead;
        ListNode after = afterHead;

        while (head != null){
            if(head.val < x){
                before.next = new ListNode(head.val);
                before = before.next;
            }else {
                after.next = new ListNode(head.val);
                after = after.next;
            }
            head = head.next;
        }

        after.next = null;

        before.next = afterHead.next;

        return beforeHead.next;

    }

以上是关于閾捐〃--鍒嗛殧閾捐〃锛坙eetcode86的主要内容,如果未能解决你的问题,请参考以下文章

閾捐〃鐨勯€嗙疆

java LinkedList(閾捐〃)

绾挎€ц〃閾捐〃瀹炵幇

閾捐〃鐨勫垱寤哄強閫嗗簭鎵撳嵃

鏁版嵁缁撴瀯锛堜竴锛夌嚎鎬ц〃寰幆閾捐〃鐩稿叧琛ュ厖