添加 problem 61

This commit is contained in:
YDZ
2019-03-08 02:38:00 +08:00
parent e669bc88cb
commit cffa85d6fe
3 changed files with 133 additions and 0 deletions

View File

@ -0,0 +1,33 @@
# [61. Rotate List](https://leetcode.com/problems/rotate-list/description/)
## 题目
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
```
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
```
Example 2:
```
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
```
## 题目大意
旋转链表 K 次。
这道题需要注意的点是K 可能很大K = 2000000000 ,如果是循环肯定会超时。应该找出 O(n) 的复杂度的算法才行。由于是循环旋转,最终状态其实是确定的,利用链表的长度取余可以得到链表的最终旋转结果。

View File

@ -0,0 +1,32 @@
package leetcode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func rotateRight(head *ListNode, k int) *ListNode {
if head == nil || head.Next == nil || k == 0 {
return head
}
newHead := &ListNode{Val: 0, Next: head}
len := 0
cur := newHead
for cur.Next != nil {
len++
cur = cur.Next
}
if (k % len) == 0 {
return head
}
cur.Next = head
cur = newHead
for i := len - k%len; i > 0; i-- {
cur = cur.Next
}
res := &ListNode{Val: 0, Next: cur.Next}
cur.Next = nil
return res.Next
}

View File

@ -0,0 +1,68 @@
package leetcode
import (
"fmt"
"testing"
)
type question61 struct {
para61
ans61
}
// para 是参数
// one 代表第一个参数
type para61 struct {
one []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans61 struct {
one []int
}
func Test_Problem61(t *testing.T) {
qs := []question61{
question61{
para61{[]int{1, 2, 3, 4, 5}, 2},
ans61{[]int{4, 5, 1, 2, 3}},
},
question61{
para61{[]int{1, 2, 3, 4, 5}, 3},
ans61{[]int{4, 5, 1, 2, 3}},
},
question61{
para61{[]int{0, 1, 2}, 4},
ans61{[]int{2, 0, 1}},
},
question61{
para61{[]int{1, 1, 1, 2}, 3},
ans61{[]int{1, 1, 2, 1}},
},
question61{
para61{[]int{1}, 10},
ans61{[]int{1}},
},
question61{
para61{[]int{}, 100},
ans61{[]int{}},
},
}
fmt.Printf("------------------------Leetcode Problem 61------------------------\n")
for _, q := range qs {
_, p := q.ans61, q.para61
fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(rotateRight(S2l(p.one), p.k)))
}
fmt.Printf("\n\n\n")
}