为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode725. 分隔链表 | Split Linked List in Parts

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10514474.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list "parts".

The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null.

The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later.

Return a List of ListNode's representing the linked list parts that are formed.

Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ]

Example 1:

Input: 
root = [1, 2, 3], k = 5
Output: [[1],[2],[3],[],[]]
Explanation:
The input and each element of the output are ListNodes, not arrays.
For example, the input root has root.val = 1, root.next.val = 2, \root.next.next.val = 3, and root.next.next.next = null.
The first element output[0] has output[0].val = 1, output[0].next = null.
The last element output[4] is null, but it's string representation as a ListNode is [].

Example 2:

Input: 
root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
Explanation:
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.

Note:

  • The length of root will be in the range [0, 1000].
  • Each value of a node in the input will be an integer in the range [0, 999].
  • k will be an integer in the range [1, 50].

给定一个头结点为 root 的链表, 编写一个函数以将链表分隔为 k 个连续的部分。

每部分的长度应该尽可能的相等: 任意两部分的长度差距不能超过 1,也就是说可能有些部分为 null。

这k个部分应该按照在链表中出现的顺序进行输出,并且排在前面的部分的长度应该大于或等于后面的长度。

返回一个符合上述规则的链表的列表。

举例: 1->2->3->4, k = 5 // 5 结果 [ [1], [2], [3], [4], null ]

示例 1:

输入: 
root = [1, 2, 3], k = 5
输出: [[1],[2],[3],[],[]]
解释:
输入输出各部分都应该是链表,而不是数组。
例如, 输入的结点 root 的 val= 1, root.next.val = 2, \root.next.next.val = 3, 且 root.next.next.next = null。
第一个输出 output[0] 是 output[0].val = 1, output[0].next = null。
最后一个元素 output[4] 为 null, 它代表了最后一个部分为空链表。

示例 2:

输入: 
root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
输出: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
解释:
输入被分成了几个连续的部分,并且每部分的长度相差不超过1.前面部分的长度大于等于后面部分的长度。

提示:

  • root 的长度范围: [0, 1000].
  • 输入的每个节点的大小范围:[0, 999].
  • k 的取值范围: [1, 50].

Runtime: 20 ms
Memory Usage: 19.7 MB
 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     public var val: Int
 5  *     public var next: ListNode?
 6  *     public init(_ val: Int) {
 7  *         self.val = val
 8  *         self.next = nil
 9  *     }
10  * }
11  */
12 class Solution {
13     func splitListToParts(_ root: ListNode?, _ k: Int) -> [ListNode?] {
14         var root = root
15         var res:[ListNode?] = [ListNode?](repeating:nil,count:k)
16         var len:Int = 0
17         var t:ListNode? = root
18         while(t != nil)
19         {
20             len += 1
21             t = t!.next
22         }
23         var avg:Int = len / k
24         var ext:Int = len % k
25         var i:Int = 0
26         while(i < k && root != nil)
27         {
28             res[i] = root
29             var num:Int = (i < ext) ? 1 : 0
30             for j in 1..<(avg + num )
31             {
32                 root = root!.next
33             }
34             var t:ListNode? = root!.next
35             root?.next = nil
36             root = t   
37             i += 1
38         }
39         return res
40     }
41 }

20ms

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     public var val: Int
 5  *     public var next: ListNode?
 6  *     public init(_ val: Int) {
 7  *         self.val = val
 8  *         self.next = nil
 9  *     }
10  * }
11  */
12 class Solution {
13     func splitListToParts(_ root: ListNode?, _ k: Int) -> [ListNode?] {
14         var result  = Array<ListNode?>(repeating: nil, count: k)
15         if nil == root {
16             return result
17         }
18         var length = 0
19         var temp : ListNode? = root
20         while nil != temp {
21             length += 1
22             temp = temp?.next
23         }
24         if k >= length {
25             temp = root
26             var i = 0
27             while nil != temp {
28                 let p = temp?.next
29                 temp?.next = nil
30                 result[i] = temp
31                 temp = p
32                 i += 1
33             }
34             return result
35         }
36         
37         let average = length / k
38         let mod =  length % k
39         var currentHead : ListNode? = root
40         for i in 0..<k {
41             temp = currentHead
42             let targetNodes = i < mod ? (average + 1) : average
43             var j : Int = 1
44             while j < targetNodes  {
45                 temp = temp?.next
46                 j += 1
47             }
48             result[i] = currentHead
49             currentHead = temp?.next
50             temp?.next = nil            
51         }
52         return result
53     }
54 }

24ms

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     public var val: Int
 5  *     public var next: ListNode?
 6  *     public init(_ val: Int) {
 7  *         self.val = val
 8  *         self.next = nil
 9  *     }
10  * }
11  */
12 class Solution {
13 func splitListToParts(_ root: ListNode?, _ k: Int) -> [ListNode?] {
14     var current = root
15     var count = 0
16     
17     while current != nil {
18         current = current?.next
19         count += 1
20     }
21     
22     let width = count / k
23     let rem = count % k
24     
25     var result: [ListNode?] = []
26     
27     current = root
28     for i in 0..<k {
29         let head = current
30         let generate = width + (i < rem ? 1 : 0) - 1
31         if generate < 0 {
32             result.append(nil)
33             continue
34         }
35         
36         for _ in 0..<generate {
37             if current != nil {
38                 current = current?.next
39             }
40         }
41         if current != nil {
42             let prev = current
43             current = current?.next
44             prev?.next = nil
45         }
46         result.append(head)
47     }    
48     return result
49   }
50 }

19288kb

 1 class Solution {
 2     func splitListToParts(_ root: ListNode?, _ k: Int) -> [ListNode?] {        
 3         if k == 0 {
 4             return [root]
 5         }        
 6         var current = root
 7         var length = 1
 8         while current?.next != nil {
 9             current = current?.next
10             length += 1
11         }        
12         var elements = length / k
13         var extras = length % k        
14         current = root        
15         var result = [ListNode?]()        
16         if elements == 0 { // k >= length
17             var counter = k            
18             while current != nil {
19                 let node = ListNode(current!.val)
20                 result.append(node)
21                 current = current?.next
22                 counter -= 1
23             }
24             while counter > 0 {
25                 result.append(current)
26                 counter -= 1
27             }
28             return result
29         }        
30         var node = current
31         while current != nil {            
32             elements -= 1            
33             if elements == 0 {                
34                 if extras > 0 {
35                     extras -= 1
36                     current = current?.next
37                 }                
38                 let next = current?.next                
39                 current?.next = nil                
40                 result.append(node)                
41                 current = next
42                 node = current                
43                 elements = length / k                
44                 continue
45             }            
46             current = current?.next
47         }        
48         return result
49     }
50 }

 

posted @ 2019-03-12 09:07  为敢技术  阅读(226)  评论(0编辑  收藏  举报