閾捐〃--鍒嗛殧閾捐〃锛坙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的主要内容,如果未能解决你的问题,请参考以下文章