/* * Author: Wang P * Version: 1.0.0 * Date: 2021-03-04 17:27:34 * Description: **/
package com.weitrue.leetcode.editor.cn;
publicclassLinkedListCycle{ publicstaticvoidmain(String[] args){ Solution s = new LinkedListCycle().new Solution(); }
//Given head, the head of a linked list, determine if the linked list has a cycl //e in it. // // There is a cycle in a linked list if there is some node in the list that can //be reached again by continuously following the next pointer. Internally, pos is //used to denote the index of the node that tail's next pointer is connected to. N //ote that pos is not passed as a parameter. // // Return true if there is a cycle in the linked list. Otherwise, return false. // // Example 1: //Input: head = [3,2,0,-4], pos = 1 //Output: true //Explanation: There is a cycle in the linked list, where the tail connects to t //he 1st node (0-indexed). // // Example 2: //Input: head = [1,2], pos = 0 //Output: true //Explanation: There is a cycle in the linked list, where the tail connects to t //he 0th node. // // Example 3: //Input: head = [1], pos = -1 //Output: false //Explanation: There is no cycle in the linked list. // // Constraints: // The number of the nodes in the list is in the range [0, 104]. // -105 <= Node.val <= 105 // pos is -1 or a valid index in the linked-list. // // Follow up: Can you solve it using O(1) (i.e. constant) memory? // Related Topics 链表 双指针 // 👍 970 👎 0
// leetcode submit region begin(Prohibit modification and deletion) classListNode{ int val; ListNode next; ListNode(int x) { val = x; next = null; } }
publicclassSolution{ publicbooleanhasCycle(ListNode head){ if (head == null || head.next == null) { returnfalse; } ListNode p = head, q = head; do { p = p.next; q = q.next.next; } while (q != null && q.next != null && p != q); return p == q; } } //leetcode submit region end(Prohibit modification and deletion) }
package leetcode /** * Author: Wang P * Version: 1.0.0 * Date: 2021-03-05 11:03:59 * Description: **/ //Given head, the head of a linked list, determine if the linked list has a cycl //e in it. // // There is a cycle in a linked list if there is some node in the list that can //be reached again by continuously following the next pointer. Internally, pos is //used to denote the index of the node that tail's next pointer is connected to. N //ote that pos is not passed as a parameter. // // Return true if there is a cycle in the linked list. Otherwise, return false. // // Example 1: //Input: head = [3,2,0,-4], pos = 1 //Output: true //Explanation: There is a cycle in the linked list, where the tail connects to t //he 1st node (0-indexed). // // Example 2: //Input: head = [1,2], pos = 0 //Output: true //Explanation: There is a cycle in the linked list, where the tail connects to t //he 0th node. // // Example 3: //Input: head = [1], pos = -1 //Output: false //Explanation: There is no cycle in the linked list. // // Constraints: // The number of the nodes in the list is in the range [0, 104]. // -105 <= Node.val <= 105 // pos is -1 or a valid index in the linked-list. // Follow up: Can you solve it using O(1) (i.e. constant) memory? // Related Topics 链表 双指针 // 👍 971 👎 0
//leetcode submit region begin(Prohibit modification and deletion) // Definition for singly-linked list. type ListNode struct { Val int Next *ListNode }
funchasCycle(head *ListNode)bool { if head == nil || head.Next == nil { returnfalse } p := head.Next q := head.Next.Next for q != nil && q.Next != nil && p != q{ p = p.Next q = q.Next.Next } return p == q } //leetcode submit region end(Prohibit modification and deletion)
""" # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list.
classListNode: def__init__(self, x): self.val = x self.next = None
classSolution:
defhasCycle(self, head: ListNode) -> bool: ifnot head: returnFalse p = ListNode(-1) p.next = head p, q = head, head.next while q and q.next: p = p.next q = q.next.next if p == q: returnTrue
returnFalse
# leetcode submit region end(Prohibit modification and deletion)
/* * Author: Wang P * Version: 1.0.0 * Date: 2021-03-04 19:03:31 * Description: 142-Linked List Cycle II **/
package com.weitrue.leetcode.editor.cn;
publicclassLinkedListCycleIi{ publicstaticvoidmain(String[] args){ Solution s = new LinkedListCycleIi().new Solution(); }
//Given a linked list, return the node where the cycle begins. If there is no cy //cle, return null. // // There is a cycle in a linked list if there is some node in the list that can //be reached again by continuously following the next pointer. Internally, pos is //used to denote the index of the node that tail's next pointer is connected to. N //ote that pos is not passed as a parameter. // // Notice that you should not modify the linked list. // // Example 1: //Input: head = [3,2,0,-4], pos = 1 //Output: tail connects to node index 1 //Explanation: There is a cycle in the linked list, where tail connects to the s //econd node. // // Example 2: //Input: head = [1,2], pos = 0 //Output: tail connects to node index 0 //Explanation: There is a cycle in the linked list, where tail connects to the f //irst node. // // Example 3: //Input: head = [1], pos = -1 //Output: no cycle //Explanation: There is no cycle in the linked list. // // Constraints: // The number of the nodes in the list is in the range [0, 104]. // -105 <= Node.val <= 105 // pos is -1 or a valid index in the linked-list. // // Follow up: Can you solve it using O(1) (i.e. constant) memory? // Related Topics 链表 双指针 // 👍 897 👎 0
// leetcode submit region begin(Prohibit modification and deletion) classListNode{ int val; ListNode next; ListNode(int x) { val = x; next = null; } }
publicclassSolution{ public ListNode detectCycle(ListNode head){ if(head == null || head.next == null){ returnnull; } ListNode p = head, q = head; do { p = p.next; q = q.next.next; } while (q != null && q.next != null && p != q); if (p != q) { returnnull; } q = head; while (p != q) { p = p.next; q = q.next; } return q; } } //leetcode submit region end(Prohibit modification and deletion)
package leetcode /** * Author: Wang P * Version: 1.0.0 * Date: 2021-03-05 11:14:26 * Description: **/ //Given a linked list, return the node where the cycle begins. If there is no cy //cle, return null. // // There is a cycle in a linked list if there is some node in the list that can //be reached again by continuously following the next pointer. Internally, pos is //used to denote the index of the node that tail's next pointer is connected to. N //ote that pos is not passed as a parameter. // // Notice that you should not modify the linked list. // // Example 1: //Input: head = [3,2,0,-4], pos = 1 //Output: tail connects to node index 1 //Explanation: There is a cycle in the linked list, where tail connects to the s //econd node. // // Example 2: //Input: head = [1,2], pos = 0 //Output: tail connects to node index 0 //Explanation: There is a cycle in the linked list, where tail connects to the f //irst node. // // Example 3: //Input: head = [1], pos = -1 //Output: no cycle //Explanation: There is no cycle in the linked list. // // Constraints: // The number of the nodes in the list is in the range [0, 104]. // -105 <= Node.val <= 105 // pos is -1 or a valid index in the linked-list.
// Follow up: Can you solve it using O(1) (i.e. constant) memory? // Related Topics 链表 双指针 // 👍 898 👎 0
//leetcode submit region begin(Prohibit modification and deletion) /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcdetectCycle(head *ListNode) *ListNode { if head == nil || head.Next == nil { returnnil } p := head.Next q := head.Next.Next for q != nil && q.Next != nil && p != q{ q = q.Next.Next p = p.Next } if p != q { returnnil } q = head for p != q { p = p.Next q = q.Next } return q } //leetcode submit region end(Prohibit modification and deletion)
""" # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list. # # classListNode: def__init__(self, x): self.val = x self.next = None
classSolution: defdetectCycle(self, head: ListNode) -> ListNode: ifnot head ornot head.next: returnNone p, q = head.next, head.next.next while q and q.nextand p != q: p = p.next q = q.next.next if p != q: returnNone q = head while p != q: p = p.next q = q.next return q
# leetcode submit region end(Prohibit modification and deletion)
/* * Author: Wang P * Version: 1.0.0 * Date: 2021-03-04 17:56:08 * Description: **/ package com.weitrue.leetcode.editor.cn;
publicclassHappyNumber{ publicstaticvoidmain(String[] args){ Solution s = new HappyNumber().new Solution(); int sum = 0; for (int i=0; i<=100000; i++) { if (s.isHappy(i)) { sum++; } } System.out.println(sum); }
//Write an algorithm to determine if a number n is happy. // // A happy number is a number defined by the following process: // // Starting with any positive integer, replace the number by the sum of the squares of its digits. // Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. // Those numbers for which this process ends in 1 are happy. // // Return true if n is a happy number, and false if not. // // Example 1: //Input: n = 19 //Output: true //Explanation: //12 + 92 = 82 //82 + 22 = 68 //62 + 82 = 100 //12 + 02 + 02 = 1 // // Example 2: //Input: n = 2 //Output: false // // Constraints: // // 1 <= n <= 231 - 1 // // Related Topics 哈希表 数学 // 👍 542 👎 0
//leetcode submit region begin(Prohibit modification and deletion) classSolution{ publicintgetNext(int n){ int x = 0; while(n > 0) { x += (n % 10) * (n % 10); n = n / 10; } return x; }
publicbooleanisHappy(int n){ int p = n, q = n; do{ p = getNext(p); q = getNext(getNext(q)); } while (p != q && q!= 1); return q == 1; } } //leetcode submit region end(Prohibit modification and deletion)
package leetcode /** * Author: Wang P * Version: 1.0.0 * Date: 2021-03-05 12:56:41 * Description: //Write an algorithm to determine if a number n is happy. // // A happy number is a number defined by the following process: // // Starting with any positive integer, replace the number by the sum of the squa //res of its digits. // Repeat the process until the number equals 1 (where it will stay), or it loop //s endlessly in a cycle which does not include 1. // Those numbers for which this process ends in 1 are happy. // // Return true if n is a happy number, and false if not. // // Example 1: //Input: n = 19 //Output: true //Explanation: //12 + 92 = 82 //82 + 22 = 68 //62 + 82 = 100 //12 + 02 + 02 = 1 // // Example 2: //Input: n = 2 //Output: false // // Constraints: // 1 <= n <= 231 - 1 // // Related Topics 哈希表 数学 // 👍 547 👎 0 **/
//leetcode submit region begin(Prohibit modification and deletion) funcIsHappy(n int)bool { p, q := getNext(n), getNext(getNext(n)) for p != q && q != 1 { p = getNext(p) q = getNext(getNext(q)) } return q == 1 }
funcgetNext(n int)int { x := 0 for n > 0 { x += (n % 10) * (n % 10) n = n / 10 } return x } //leetcode submit region end(Prohibit modification and deletion)
/* * Author: Wang P * Version: 1.0.0 * Date: 2021-03-05 17:30:32 * Description: 206-Reverse Linked List **/
package com.weitrue.leetcode.editor.cn;
publicclassReverseLinkedList{ publicstaticvoidmain(String[] args){ Solution s = new ReverseLinkedList().new Solution(); }
//Given the head of a singly linked list, reverse the list, and return the reversed list. // // Example 1: //Input: head = [1,2,3,4,5] //Output: [5,4,3,2,1] // // Example 2: //Input: head = [1,2] //Output: [2,1] // // Example 3: //Input: head = [] //Output: [] // // Constraints: // The number of nodes in the list is the range [0, 5000]. // -5000 <= Node.val <= 5000 // // Follow up: A linked list can be reversed either iteratively or recursively. C //ould you implement both? // Related Topics 链表 // 👍 1568 👎 0
classSolution{ public ListNode reverseList(ListNode head){ ListNode pre = null, cur = head, next = null; while (cur != null) { next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } } //leetcode submit region end(Prohibit modification and deletion)
package leetcode /** * Author: Wang P * Version: 1.0.0 * Date: 2021-03-05 17:46:07 * Description: //Given the head of a singly linked list, reverse the list, and return the reversed list. // Example 1: //Input: head = [1,2,3,4,5] //Output: [5,4,3,2,1] // // Example 2: //Input: head = [1,2] //Output: [2,1] // // Example 3: //Input: head = [] //Output: [] // // Constraints: // The number of nodes in the list is the range [0, 5000]. // -5000 <= Node.val <= 5000 // // Follow up: A linked list can be reversed either iteratively or recursively. C //ould you implement both? // Related Topics 链表 // 👍 1568 👎 0 **/ //leetcode submit region begin(Prohibit modification and deletion) /** * Definition for singly-linked list. */ type ListNode struct { Val int Next *ListNode }
funcreverseList(head *ListNode) *ListNode { var pre, cur, next *ListNode = nil, head, nil for cur != nil { next = cur.Next cur.Next = pre pre = cur cur = next } return pre } //leetcode submit region end(Prohibit modification and deletion)
""" # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list. classListNode: def__init__(self, val=0, next=None): self.val = val self.next = next
classSolution: defreverseList(self, head: ListNode) -> ListNode: pre, cur, nex = None, head, None while cur: nex = cur.next cur.next = pre pre = cur cur = nex return pre # leetcode submit region end(Prohibit modification and deletion)
Solution s = new ReverseLinkedListIi().new Solution(); ListNode n5 = new ReverseLinkedListIi().new ListNode(5, null); ListNode n4 = new ReverseLinkedListIi().new ListNode(4, n5); ListNode n3 = new ReverseLinkedListIi().new ListNode(3, n4); ListNode n2 = new ReverseLinkedListIi().new ListNode(2, n3); ListNode n1 = new ReverseLinkedListIi().new ListNode(1, n2); ListNode n = s.reverseBetween(n1, 2, 4); while (n != null && n.val > 0) { System.out.print(n.val); System.out.print("->"); n = n.next; } }
//Given the head of a singly linked list and two integers left and right where left <= right, // reverse the nodes of the list from position left to position right, and return the reversed list. // // Example 1: //Input: head = [1,2,3,4,5], left = 2, right = 4 //Output: [1,4,3,2,5] // // Example 2: //Input: head = [5], left = 1, right = 1 //Output: [5] // // Constraints: // The number of nodes in the list is n. // 1 <= n <= 500 // -500 <= Node.val <= 500 // 1 <= left <= right <= n // //Follow up: Could you do it in one pass? Related Topics 链表 // 👍 709 👎 0
classSolution{ public ListNode reverseBetween(ListNode head, int left, int right){ // 需要虚拟节点 ListNode hair = new ListNode(0, head), cur = hair ; int n = right - left + 1; while (left > 1) { cur = cur.next; left--; } cur.next = reverse(cur.next, n); return hair.next; }
public ListNode reverse(ListNode head, int x){ // 从头节点开始,反转n个节点 ListNode pre = new ListNode(0), cur = head, next = null; while (x > 0) { next = cur.next; cur.next = pre.next; pre.next = cur; cur = next; x--; } head.next = cur; return pre.next; }
public ListNode reverseN(ListNode head, int n){ // 递归方式 if (n == 1) { return head; } ListNode tail = head.next, p = reverseN(head.next, n-1); head.next = tail.next; tail.next = head; return p; } } //leetcode submit region end(Prohibit modification and deletion)
/** * Author: Wang P * Version: 1.0.0 * Date: 2021-03-05 19:07:45 * Description: //Given the head of a singly linked list and two integers left and right where left <= right, reverse //the nodes of the list from position left to position right, and return the reversed list. // // Example 1: //Input: head = [1,2,3,4,5], left = 2, right = 4 //Output: [1,4,3,2,5] // // Example 2: //Input: head = [5], left = 1, right = 1 //Output: [5] // // Constraints: // The number of nodes in the list is n. // 1 <= n <= 500 // -500 <= Node.val <= 500 // 1 <= left <= right <= n //Follow up: Could you do it in one pass? Related Topics 链表 // 👍 709 👎 0
**/ //leetcode submit region begin(Prohibit modification and deletion) /** * Definition for singly-linked list. */ type ListNode struct { Val int Next *ListNode }
funcreverseBetween(head *ListNode, left int, right int) *ListNode { hair := &ListNode{Next:head} cur := hair n := right - left + 1 for left > 1 { cur = cur.Next left-- } cur.Next = reverse(cur.Next, n) return hair.Next }
funcreverse(head *ListNode, n int) *ListNode { pre, next := &ListNode{}, &ListNode{} cur := head
for n > 0 { next = cur.Next cur.Next = pre.Next pre.Next = cur cur = next n-- } head.Next = cur return pre.Next }
//leetcode submit region end(Prohibit modification and deletion)
""" Module Description: 92-反转链表 II Solution: Date: 2021-03-05 19:06:58 Author: Wang P Problem:# 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 # # 说明: # 1 ≤ m ≤ n ≤ 链表长度。 # # 示例: # # 输入: 1->2->3->4->5->NULL, m = 2, n = 4 # 输出: 1->4->3->2->5->NULL # Related Topics 链表 # 👍 709 👎 0 """ # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list.
# class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next
classSolution: defreverseBetween(self, head: ListNode, left: int, right: int) -> ListNode: cur = hair = ListNode(next=head) n = right - left + 1 while left > 1: cur = cur.next left -= 1
pre, cur, nex = ListNode(), head, None while n > 0: nex = cur.next cur.next = pre.next pre.next = cur cur = nex n -= 1 head.next = cur return pre.next # leetcode submit region end(Prohibit modification and deletion)
/* * Author: Wang P * Version: 1.0.0 * Date: 2021-03-06 17:42:34 * Description: 25-Reverse Nodes in k-Group **/
package com.weitrue.leetcode.editor.cn;
publicclassReverseNodesInKGroup{ publicstaticvoidmain(String[] args){ Solution s = new ReverseNodesInKGroup().new Solution(); }
//Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. //k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. // Follow up: // Could you solve the problem in O(1) extra memory space? // You may not alter the values in the list's nodes, only nodes itself may be changed.
// Example 1: //Input: head = [1,2,3,4,5], k = 2 //Output: [2,1,4,3,5]
// Example 2: //Input: head = [1,2,3,4,5], k = 3 //Output: [3,2,1,4,5]
// Example 3: //Input: head = [1,2,3,4,5], k = 1 //Output: [1,2,3,4,5]
// Example 4: //Input: head = [1], k = 1 //Output: [1]
// Constraints: // The number of nodes in the list is in the range sz. // 1 <= sz <= 5000 // 0 <= Node.val <= 1000 // 1 <= k <= sz // // Related Topics 链表 // 👍 977 👎 0
/** * Author: Wang P * Version: 1.0.0 * Date: 2021-03-18 18:38:00 * Description: //Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. // k is a positive integer and is less than or equal to the length of the linked // list. If the number of nodes is not a multiple of k then left-out nodes, in the // end, should remain as it is. // Follow up: // Could you solve the problem in O(1) extra memory space? // You may not alter the values in the list's nodes, only nodes itself may be changed. // // Example 1: //Input: head = [1,2,3,4,5], k = 2 //Output: [2,1,4,3,5] // // Example 2: //Input: head = [1,2,3,4,5], k = 3 //Output: [3,2,1,4,5] // // Example 3: //Input: head = [1,2,3,4,5], k = 1 //Output: [1,2,3,4,5] // // Example 4: //Input: head = [1], k = 1 //Output: [1] // // Constraints: // The number of nodes in the list is in the range sz. // 1 <= sz <= 5000 // 0 <= Node.val <= 1000 // 1 <= k <= sz // Related Topics 链表 // 👍 977 👎 0
**/ //leetcode submit region begin(Prohibit modification and deletion) /** * Definition for singly-linked list. */ type ListNode struct { Val int Next *ListNode }
funcreverseKGroup(head *ListNode, k int) *ListNode { hair := &ListNode{Next:head} pre, tail := hair, hair for head != nil { for i := 0; i < k; i++ { tail = tail.Next if tail == nil { return hair.Next } }
head, tail = reverseK(head, tail) pre.Next = head pre = tail head = pre.Next } return hair.Next }
# leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list.
classListNode: def__init__(self, val=0, next=None): self.val = val self.next = next
classSolution: defreverseKGroup(self, head: ListNode, k: int) -> ListNode: tail = pre = hair = ListNode(next=head) while head: # tail = pre for i inrange(0, k): tail = tail.next ifnot tail: return hair.next
head, tail = self.reverse(head, tail) pre.next = head pre = tail head = pre.next
return hair.next
defreverse(self, head, tail: ListNode) -> (ListNode, ListNode): pre, cur, nex = tail.next, head, None while pre != tail: nex = cur.next cur.next = pre pre = cur cur = nex
return tail, head
# leetcode submit region end(Prohibit modification and deletion)
Solution s = new RotateList().new Solution(); ListNode n5 = new RotateList().new ListNode(5, null); ListNode n4 = new RotateList().new ListNode(4, n5); ListNode n3 = new RotateList().new ListNode(3, n4); ListNode n2 = new RotateList().new ListNode(2, n3); ListNode n1 = new RotateList().new ListNode(1, n2); ListNode n = s.rotateRight(n1, 2);
while (n != null) { System.out.print(n.val); System.out.print("->"); n = n.next; } }
//Given the head of a linked list, rotate the list to the right by k places. // // Example 1: //Input: head = [1,2,3,4,5], k = 2 //Output: [4,5,1,2,3] // // Example 2: //Input: head = [0,1,2], k = 4 //Output: [2,0,1] // // Constraints: // The number of nodes in the list is in the range [0, 500]. // -100 <= Node.val <= 100 // 0 <= k <= 2 * 109 // // Related Topics 链表 双指针 // 👍 444 👎 0
/** * Author: Wang P * Version: 1.0.0 * Date: 2021-03-06 20:26:17 * Description: Given the head of a linked list, rotate the list to the right by k places.
Example 1: Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3]
Example 2: Input: head = [0,1,2], k = 4 Output: [2,0,1]
Constraints: The number of nodes in the list is in the range [0, 500]. -100 <= Node.val <= 100 0 <= k <= 2 * 109
Related Topics 链表 双指针 👍 444 👎 0 **/ //leetcode submit region begin(Prohibit modification and deletion) /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcrotateRight(head *ListNode, k int) *ListNode { if head == nil || head.Next == nil { return head } oldTail := head length := 1 for oldTail.Next != nil { oldTail = oldTail.Next length++ } oldTail.Next = head newTail := head for i := 0; i < length - k%length -1; i++ { newTail = newTail.Next } head = newTail.Next newTail.Next = nil return head } //leetcode submit region end(Prohibit modification and deletion)
/* * Author: Wang P * Version: 1.0.0 * Date: 2021-03-06 20:22:33 * Description: 24-Swap Nodes in Pairs **/
package com.weitrue.leetcode.editor.cn;
publicclassSwapNodesInPairs{ publicstaticvoidmain(String[] args){ Solution s = new SwapNodesInPairs().new Solution();
}
//Given a linked list, swap every two adjacent nodes and return its head. // // Example 1: //Input: head = [1,2,3,4] //Output: [2,1,4,3] // // Example 2: //Input: head = [] //Output: [] // // Example 3: //Input: head = [1] //Output: [1] // // Constraints: // The number of nodes in the list is in the range [0, 100]. // 0 <= Node.val <= 100 //Follow up: Can you solve the problem without modifying the values in the list' //s nodes? (i.e., Only nodes themselves may be changed.) Related Topics 递归 链表 // 👍 859 👎 0
package leetcode /** * Author: Wang P * Version: 1.0.0 * Date: 2021-03-06 20:26:56 * Description: Given a linked list, swap every two adjacent nodes and return its head.
Example 1: Input: head = [1,2,3,4] Output: [2,1,4,3]
Example 2: Input: head = [] Output: []
Example 3: Input: head = [1] Output: [1]
Constraints: The number of nodes in the list is in the range [0, 100]. 0 <= Node.val <= 100
Follow up: Can you solve the problem without modifying the values in the list' s nodes? (i.e., Only nodes themselves may be changed.) Related Topics 递归 链表 👍 859 👎 0 **/ //leetcode submit region begin(Prohibit modification and deletion) /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcswapPairs(head *ListNode) *ListNode { hair := &ListNode{Next:head} pre, tail := hair, hair for head != nil { for i := 0; i < 2; i++ { tail = tail.Next if tail == nil { return hair.Next } }
head, tail = reverseN(head, tail) pre.Next = head pre = tail head = pre.Next } return hair.Next }
""" Module Description: 24-两两交换链表中的节点 Solution: Date: 2021-03-06 20:25:15 Author: Wang P Problem: 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1: 输入:head = [1,2,3,4] 输出:[2,1,4,3]
示例 2: 输入:head = [] 输出:[]
示例 3: 输入:head = [1] 输出:[1]
提示: 链表中节点的数目在范围 [0, 100] 内 0 <= Node.val <= 100 进阶:你能在不修改链表节点值的情况下解决这个问题吗?(也就是说,仅修改节点本身。) Related Topics 递归 链表 👍 859 👎 0 """ # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list.
classListNode: def__init__(self, val=0, next=None): self.val = val self.next = next
classSolution:
defswapPairs(self, head: ListNode) -> ListNode: tail = pre = hair = ListNode(next=head) while head: # tail = pre for i inrange(0, 2): tail = tail.next ifnot tail: return hair.next
head, tail = self.reverse(head, tail) pre.next = head pre = tail head = pre.next
return hair.next
defreverse(self, head, tail: ListNode) -> (ListNode, ListNode): pre, cur, nex = tail.next, head, None while pre != tail: nex = cur.next cur.next = pre pre = cur cur = nex
return tail, head # leetcode submit region end(Prohibit modification and deletion)
/* * Author: Wang P * Version: 1.0.0 * Date: 2021-03-05 12:54:46 * Description: 19-Remove Nth Node From End of List **/
package com.weitrue.leetcode.editor.cn;
publicclassRemoveNthNodeFromEndOfList{ publicstaticvoidmain(String[] args){ Solution s = new RemoveNthNodeFromEndOfList().new Solution(); }
//Given the head of a linked list, remove the nth node from the end of the list //and return its head. // // Follow up: Could you do this in one pass? // // Example 1: //Input: head = [1,2,3,4,5], n = 2 //Output: [1,2,3,5] // // Example 2: //Input: head = [1], n = 1 //Output: [] // // Example 3: //Input: head = [1,2], n = 1 //Output: [1]
// Constraints: // The number of nodes in the list is sz. // 1 <= sz <= 30 // 0 <= Node.val <= 100 // 1 <= n <= sz // // Related Topics 链表 双指针 // 👍 1264 👎 0
classSolution{ public ListNode removeNthFromEnd(ListNode head, int n){ ListNode hair = new ListNode(0, head), fast = head, slow = hair; while (n > 0){ fast = fast.next; n--; }
while (fast != null) { fast = fast.next; slow = slow.next; } slow.next = slow.next.next; return hair.next; } } //leetcode submit region end(Prohibit modification and deletion)
/** * Author: Wang P * Version: 1.0.0 * Date: 2021-03-05 13:43:33 * Description: **/ //Given the head of a linked list, remove the nth node from the end of the list //and return its head. // // Follow up: Could you do this in one pass? // // Example 1: //Input: head = [1,2,3,4,5], n = 2 //Output: [1,2,3,5] // // Example 2: //Input: head = [1], n = 1 //Output: [] // // Example 3: //Input: head = [1,2], n = 1 //Output: [1]
// Constraints: // The number of nodes in the list is sz. // 1 <= sz <= 30 // 0 <= Node.val <= 100 // 1 <= n <= sz // // Related Topics 链表 双指针 // 👍 1264 👎 0
//leetcode submit region begin(Prohibit modification and deletion) /** * Definition for singly-linked list. */ type ListNode struct { Val int Next *ListNode }
funcremoveNthFromEnd(head *ListNode, n int) *ListNode { hair := &ListNode{Next:head} fast, slow := head, hair for n > 0 { fast = fast.Next n-- } for fast != nil { fast = fast.Next slow = slow.Next } slow.Next = slow.Next.Next return hair.Next } //leetcode submit region end(Prohibit modification and deletion)
""" Module Description: 19-删除链表的倒数第 N 个结点 Solution: Date: 2021-03-05 13:39:13 Author: Wang P Problem:# 给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。 # # 进阶:你能尝试使用一趟扫描实现吗?
# 示例 1: # 输入:head = [1,2,3,4,5], n = 2 # 输出:[1,2,3,5] # # 示例 2: # 输入:head = [1], n = 1 # 输出:[] # # 示例 3: # 输入:head = [1,2], n = 1 # 输出:[1] # # 提示: # 链表中结点的数目为 sz # 1 <= sz <= 30 # 0 <= Node.val <= 100 # 1 <= n <= sz # # Related Topics 链表 双指针 # 👍 1264 👎 0 """ # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list. classListNode: def__init__(self, val=0, next=None): self.val = val self.next = next
classSolution: defremoveNthFromEnd(self, head: ListNode, n: int) -> ListNode: hair = ListNode(next=head) slow, fast = hair, head; while n > 0: fast = fast.next n -= 1
while fast: fast = fast.next slow = slow.next
slow.next = slow.next.next return hair.next # leetcode submit region end(Prohibit modification and deletion)
/* * Author: Wang P * Version: 1.0.0 * Date: 2021-03-05 13:48:45 * Description: 83-Remove Duplicates from Sorted List **/
package com.weitrue.leetcode.editor.cn;
publicclassRemoveDuplicatesFromSortedList{ publicstaticvoidmain(String[] args){ Solution s = new RemoveDuplicatesFromSortedList().new Solution(); }
//Given the head of a sorted linked list, delete all duplicates such that each e //lement appears only once. Return the linked list sorted as well.
// Example 1: //Input: head = [1,1,2] //Output: [1,2]
// Example 2: //Input: head = [1,1,2,3,3] //Output: [1,2,3]
// Constraints: // The number of nodes in the list is in the range [0, 300]. // -100 <= Node.val <= 100 // The list is guaranteed to be sorted in ascending order. // // Related Topics 链表 // 👍 488 👎 0
/** * Author: Wang P * Version: 1.0.0 * Date: 2021-03-05 13:50:35 * Description: //Given the head of a sorted linked list, delete all duplicates such that each e //lement appears only once. Return the linked list sorted as well. // // Example 1: //Input: head = [1,1,2] //Output: [1,2] // // Example 2: //Input: head = [1,1,2,3,3] //Output: [1,2,3] // // Constraints: // The number of nodes in the list is in the range [0, 300]. // -100 <= Node.val <= 100 // The list is guaranteed to be sorted in ascending order. // // Related Topics 链表 // 👍 488 👎 0 **/
//leetcode submit region begin(Prohibit modification and deletion) /** * Definition for singly-linked list. */ type ListNode struct { Val int Next *ListNode }
funcdeleteDuplicates(head *ListNode) *ListNode { cur := head for cur != nil && cur.Next != nil { if cur.Val == cur.Next.Val { cur.Next = cur.Next.Next }else { cur = cur.Next } } return head } //leetcode submit region end(Prohibit modification and deletion)
/* * Author: Wang P * Version: 1.0.0 * Date: 2021-03-05 13:50:14 * Description: 82-Remove Duplicates from Sorted List II **/
package com.weitrue.leetcode.editor.cn;
publicclassRemoveDuplicatesFromSortedListIi{ publicstaticvoidmain(String[] args){ Solution s = new RemoveDuplicatesFromSortedListIi().new Solution(); }
//Given the head of a sorted linked list, delete all nodes that have duplicate numbers, //leaving only distinct numbers from the original list. Return the linked //list sorted as well. // // Example 1: //Input: head = [1,2,3,3,4,4,5] //Output: [1,2,5] // // Example 2: //Input: head = [1,1,1,2,3] //Output: [2,3] // // Constraints: // The number of nodes in the list is in the range [0, 300]. // -100 <= Node.val <= 100 // The list is guaranteed to be sorted in ascending order. // // Related Topics 链表 // 👍 469 👎 0
package leetcode /** * Author: Wang P * Version: 1.0.0 * Date: 2021-03-05 13:50:38 * Description: //Given the head of a sorted linked list, delete all nodes that have duplicate n //umbers, leaving only distinct numbers from the original list. Return the linked //list sorted as well. // Example 1: //Input: head = [1,2,3,3,4,4,5] //Output: [1,2,5] // // Example 2: //Input: head = [1,1,1,2,3] //Output: [2,3] // // Constraints: // The number of nodes in the list is in the range [0, 300]. // -100 <= Node.val <= 100 // The list is guaranteed to be sorted in ascending order. // // Related Topics 链表 // 👍 469 👎 0 **/
//leetcode submit region begin(Prohibit modification and deletion) /** * Definition for singly-linked list. */ type ListNode struct { Val int Next *ListNode }
funcdeleteDuplicates(head *ListNode) *ListNode { hair := &ListNode{Next: head} fast, slow := head, hair for fast != nil { for fast.Next != nil && fast.Val == fast.Next.Val { fast = fast.Next } if slow.Next == fast{ slow = slow.Next } else { slow.Next = fast.Next } fast = fast.Next } return hair.Next } //leetcode submit region end(Prohibit modification and deletion)
/* * Author: Wang P * Version: 1.0.0 * Date: 2021-03-06 20:29:46 * Description: 86-Partition List **/
package com.weitrue.leetcode.editor.cn;
publicclassPartitionList{ publicstaticvoidmain(String[] args){ Solution s = new PartitionList().new Solution(); }
// Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. // You should preserve the original relative order of the nodes in each of the two partitions. // // Example 1: //Input: head = [1,4,3,2,5,2], x = 3 //Output: [1,2,2,4,3,5] // // Example 2: //Input: head = [2,1], x = 2 //Output: [1,2] // // Constraints: // The number of nodes in the list is in the range [0, 200]. // -100 <= Node.val <= 100 // -200 <= x <= 200 // // Related Topics 链表 双指针 // 👍 378 👎 0
package leetcode /** * Author: Wang P * Version: 1.0.0 * Date: 2021-03-06 20:37:43 * Description: Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. Example 1: Input: head = [1,4,3,2,5,2], x = 3 Output: [1,2,2,4,3,5]
Example 2: Input: head = [2,1], x = 2 Output: [1,2]
Constraints: The number of nodes in the list is in the range [0, 200]. -100 <= Node.val <= 100 -200 <= x <= 200
Related Topics 链表 双指针 👍 378 👎 0 **/ //leetcode submit region begin(Prohibit modification and deletion) /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */
funcpartition(head *ListNode, x int) *ListNode { lesser, greater := &ListNode{Next:head}, &ListNode{Next:head} less, great := lesser, greater for head != nil { if head.Val < x { less.Next = head less = less.Next } else { great.Next = head great = great.Next } head = head.Next } great.Next = nil less.Next = greater.Next
return lesser.Next } //leetcode submit region end(Prohibit modification and deletion)
""" Module Description: 86-分隔链表 Solution: Date: 2021-03-06 20:33:40 Author: Wang P Problem: 给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。 你应当 保留 两个分区中每个节点的初始相对位置。
示例 1: 输入:head = [1,4,3,2,5,2], x = 3 输出:[1,2,2,4,3,5]
/* * Author: Wang P * Version: 1.0.0 * Date: 2021-03-06 20:31:24 * Description: 138-Copy List with Random Pointer **/
package com.weitrue.leetcode.editor.cn;
publicclassCopyListWithRandomPointer{ publicstaticvoidmain(String[] args){ Solution s = new CopyListWithRandomPointer().new Solution(); }
//A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null. // // Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corre //sponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original li //st and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. // // For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y. // // Return the head of the copied linked list. // // The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where: // // val: an integer representing Node.val // random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node. // // Your code will only be given the head of the original linked list. // // Example 1: //Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]] //Output: [[7,null],[13,0],[11,4],[10,2],[1,0]] // // Example 2: //Input: head = [[1,1],[2,1]] //Output: [[1,1],[2,1]] // // Example 3: //Input: head = [[3,null],[3,0],[3,null]] //Output: [[3,null],[3,0],[3,null]] // // Example 4: //Input: head = [] //Output: [] //Explanation: The given linked list is empty (null pointer), so return null. // // Constraints: // 0 <= n <= 1000 // -10000 <= Node.val <= 10000 // Node.random is null or is pointing to some node in the linked list. // // Related Topics 哈希表 链表 // 👍 519 👎 0
//leetcode submit region begin(Prohibit modification and deletion) /* // Definition for a Node.
package leetcode /** * Author: Wang P * Version: 1.0.0 * Date: 2021-03-18 20:37:49 * Description: A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.
Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corre sponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original li st and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.
For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.
Return the head of the copied linked list.
The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:
val: an integer representing Node.val random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node.
Your code will only be given the head of the original linked list.
Example 1: Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]] Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
Example 2: Input: head = [[1,1],[2,1]] Output: [[1,1],[2,1]]
Example 3: Input: head = [[3,null],[3,0],[3,null]] Output: [[3,null],[3,0],[3,null]]
Example 4: Input: head = [] Output: [] Explanation: The given linked list is empty (null pointer), so return null.
Constraints: 0 <= n <= 1000 -10000 <= Node.val <= 10000 Node.random is null or is pointing to some node in the linked list.
Related Topics 哈希表 链表 👍 519 👎 0 **/
//leetcode submit region begin(Prohibit modification and deletion) /** * Definition for a Node. */ type Node struct { Val int Next *Node Random *Node }
funccopyRandomList(head *Node) *Node { if head == nil { returnnil } cur := head for cur != nil { n := &Node{Val:cur.Val, Next:cur.Next} cur.Next = n cur = n.Next }
cur = head for cur != nil && cur.Next != nil { if cur.Random != nil { cur.Next.Random = cur.Random.Next }else { cur.Next.Random = nil } cur = cur.Next.Next }
cur = head newNode, next := head.Next, head.Next for cur != nil && cur.Next != nil { cur.Next = cur.Next.Next if next.Next != nil { next.Next = next.Next.Next }else { next.Next = nil } cur = cur.Next next = next.Next } return newNode } //leetcode submit region end(Prohibit modification and deletion)
""" Module Description: 138-复制带随机指针的链表 Solution: Date: 2021-03-06 20:33:56 Author: Wang P Problem: 给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。 构造这个链表的 深拷贝。 深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。 例如,如果原链表中有 X 和 Y 两个节点,其中 X.random --> Y 。那么在复制链表中对应的两个节点 x 和 y ,同样有 x.random--> y 。 返回复制链表的头节点。 用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示: val:一个表示 Node.val 的整数。 random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为 null 。 你的代码 只 接受原链表的头节点 head 作为传入参数。
cur = head while cur: n = Node(x=cur.val, next=cur.next) cur.next = n cur = n.next
cur = head while cur and cur.next: cur.next.random = cur.random.nextif cur.random elseNone cur = cur.next.next
cur = head new_node = nex = head.next while cur and nex: cur.next = cur.next.next nex.next = nex.next.nextif nex.nextelseNone cur = cur.next nex = nex.next
return new_node
# leetcode submit region end(Prohibit modification and deletion)
//Design your implementation of the circular double-ended queue (deque). // Your implementation should support following operations: // // MyCircularDeque(k): Constructor, set the size of the deque to be k. // insertFront(): Adds an item at the front of Deque. Return true if the operation is successful. // insertLast(): Adds an item at the rear of Deque. Return true if the operationis successful. // deleteFront(): Deletes an item from the front of Deque. Return true if the operation is successful. // deleteLast(): Deletes an item from the rear of Deque. Return true if the operation is successful. // getFront(): Gets the front item from the Deque. If the deque is empty, return-1. // getRear(): Gets the last item from Deque. If the deque is empty, return -1. // isEmpty(): Checks whether Deque is empty or not. // isFull(): Checks whether Deque is full or not. // // Example: //MyCircularDeque circularDeque = new MycircularDeque(3); // set the size to be //3 //circularDeque.insertLast(1); // return true //circularDeque.insertLast(2); // return true //circularDeque.insertFront(3); // return true //circularDeque.insertFront(4); // return false, the queue is full //circularDeque.getRear(); // return 2 //circularDeque.isFull(); // return true //circularDeque.deleteLast(); // return true //circularDeque.insertFront(4); // return true //circularDeque.getFront(); // return 4 // // Note: // All values will be in the range of [0, 1000]. // The number of operations will be in the range of [1, 1000]. // Please do not use the built-in Deque library. // // Related Topics 设计 队列 // 👍 77 👎 0
//leetcode submit region begin(Prohibit modification and deletion) classMyCircularDeque{
/** Initialize your data structure here. Set the size of the deque to be k. */ publicMyCircularDeque(int k){ queue = newint[k]; capacity = k; count = 0; front = 0; rear = 0; }
/** Adds an item at the front of Deque. Return true if the operation is successful. */ publicbooleaninsertFront(int value){ if (isFull()) returnfalse; front = (front -1 + capacity) % capacity; queue[front] = value; count++; returntrue; }
/** Adds an item at the rear of Deque. Return true if the operation is successful. */ publicbooleaninsertLast(int value){ if (isFull()) returnfalse; queue[rear++] = value; rear %= capacity; count++; returntrue; }
/** Deletes an item from the front of Deque. Return true if the operation is successful. */ publicbooleandeleteFront(){ if (isEmpty()) returnfalse; front = (front + 1) % capacity; count--; returntrue; }
/** Deletes an item from the rear of Deque. Return true if the operation is successful. */ publicbooleandeleteLast(){ if (isEmpty()) returnfalse; rear = (rear -1 + capacity) % capacity; count--; returntrue; }
/** Get the front item from the deque. */ publicintgetFront(){ if (isEmpty()) return -1; return queue[front]; }
/** Get the last item from the deque. */ publicintgetRear(){ if (isEmpty()) return -1; return queue[(rear-1+capacity)%capacity]; }
/** Checks whether the circular deque is empty or not. */ publicbooleanisEmpty(){ return count == 0; }
/** Checks whether the circular deque is full or not. */ publicbooleanisFull(){ return count == capacity; } }
/** * Your MyCircularDeque object will be instantiated and called as such: * MyCircularDeque obj = new MyCircularDeque(k); * boolean param_1 = obj.insertFront(value); * boolean param_2 = obj.insertLast(value); * boolean param_3 = obj.deleteFront(); * boolean param_4 = obj.deleteLast(); * int param_5 = obj.getFront(); * int param_6 = obj.getRear(); * boolean param_7 = obj.isEmpty(); * boolean param_8 = obj.isFull(); */ //leetcode submit region end(Prohibit modification and deletion)
type MyCircularDeque struct { queue []int front int rear int capacity int count int }
/** Initialize your data structure here. Set the size of the deque to be k. */ funcConstructor(k int)MyCircularDeque { return MyCircularDeque{ queue: make([]int, k), capacity: k, } }
/** Adds an item at the front of Deque. Return true if the operation is successful. */ func(this *MyCircularDeque)InsertFront(value int)bool { if this.IsFull() { returnfalse } this.front = (this.front - 1 + this.capacity) % this.capacity this.queue[this.front] = value this.count += 1 returntrue }
/** Adds an item at the rear of Deque. Return true if the operation is successful. */ func(this *MyCircularDeque)InsertLast(value int)bool { if this.IsFull() { returnfalse } this.queue[this.rear] = value this.rear = (this.rear +1) % this.capacity this.count += 1 returntrue }
/** Deletes an item from the front of Deque. Return true if the operation is successful. */ func(this *MyCircularDeque)DeleteFront()bool { if this.IsEmpty() { returnfalse } this.front = (this.front +1) % this.capacity this.count -= 1 returntrue }
/** Deletes an item from the rear of Deque. Return true if the operation is successful. */ func(this *MyCircularDeque)DeleteLast()bool { if this.IsEmpty() { returnfalse } this.rear = (this.rear - 1 + this.capacity) % this.capacity this.count -= 1 returntrue }
/** Get the front item from the deque. */ func(this *MyCircularDeque)GetFront()int { if this.IsEmpty() { return-1 } return this.queue[this.front] }
/** Get the last item from the deque. */ func(this *MyCircularDeque)GetRear()int { if this.IsEmpty() { return-1 } return this.queue[(this.rear-1+this.capacity)%this.capacity] }
/** Checks whether the circular deque is empty or not. */ func(this *MyCircularDeque)IsEmpty()bool { return this.count == 0 }
/** Checks whether the circular deque is full or not. */ func(this *MyCircularDeque)IsFull()bool { return this.count == this.capacity }
def__init__(self, k: int): """ Initialize your data structure here. Set the size of the deque to be k. """ self.queue = [] self.capacity = k self.count = 0 self.front = 0 self.rear = 0 for i inrange(0, k): self.queue.append(-1)
definsertFront(self, value: int) -> bool: """ Adds an item at the front of Deque. Return true if the operation is successful. """ if self.isFull(): returnFalse self.front = (self.front - 1 + self.capacity) % self.capacity self.queue[self.front] = value self.count += 1 returnTrue
definsertLast(self, value: int) -> bool: """ Adds an item at the rear of Deque. Return true if the operation is successful. """ if self.isFull(): returnFalse self.queue[self.rear] = value self.rear = (self.rear + 1) % self.capacity self.count += 1 returnTrue
defdeleteFront(self) -> bool: """ Deletes an item from the front of Deque. Return true if the operation is successful. """ if self.isEmpty(): returnFalse
defdeleteLast(self) -> bool: """ Deletes an item from the rear of Deque. Return true if the operation is successful. """ if self.isEmpty(): returnFalse
defgetFront(self) -> int: """ Get the front item from the deque. """ return -1if self.isEmpty() else self.queue[self.front]
defgetRear(self) -> int: """ Get the last item from the deque. """ return -1if self.isEmpty() else self.queue[(self.rear - 1 + self.capacity) % self.capacity]
defisEmpty(self) -> bool: """ Checks whether the circular deque is empty or not. """ return self.count == 0
defisFull(self) -> bool: """ Checks whether the circular deque is full or not. """ return self.count == self.capacity
# Your MyCircularDeque object will be instantiated and called as such: # obj = MyCircularDeque(k) # param_1 = obj.insertFront(value) # param_2 = obj.insertLast(value) # param_3 = obj.deleteFront() # param_4 = obj.deleteLast() # param_5 = obj.getFront() # param_6 = obj.getRear() # param_7 = obj.isEmpty() # param_8 = obj.isFull() # leetcode submit region end(Prohibit modification and deletion)
publicclassDesignFrontMiddleBackQueue{ publicstaticvoidmain(String[] args){ FrontMiddleBackQueue s = new DesignFrontMiddleBackQueue().new FrontMiddleBackQueue(); }
//Design a queue that supports push and pop operations in the front, middle, and back. // Implement the FrontMiddleBack class: // // FrontMiddleBack() Initializes the queue. // void pushFront(int val) Adds val to the front of the queue. // void pushMiddle(int val) Adds val to the middle of the queue. // void pushBack(int val) Adds val to the back of the queue. // int popFront() Removes the front element of the queue and returns it. If the queue is empty, return -1. // int popMiddle() Removes the middle element of the queue and returns it. If the queue is empty, return -1. // int popBack() Removes the back element of the queue and returns it. If the queue is empty, return -1. // // Notice that when there are two middle position choices, the operation is performed on the frontmost middle position choice. For example: // // Pushing 6 into the middle of [1, 2, 3, 4, 5] results in [1, 2, 6, 3, 4, 5]. // Popping the middle from [1, 2, 3, 4, 5, 6] returns 3 and results in [1, 2, 4, 5, 6]. // // Example 1: // //Input: //["FrontMiddleBackQueue", "pushFront", "pushBack", "pushMiddle", "pushMiddle", //"popFront", "popMiddle", "popMiddle", "popBack", "popFront"] //[[], [1], [2], [3], [4], [], [], [], [], []] //Output: //[null, null, null, null, null, 1, 3, 4, 2, -1] // //Explanation: //FrontMiddleBackQueue q = new FrontMiddleBackQueue(); //q.pushFront(1); // [1] //q.pushBack(2); // [1, 2] //q.pushMiddle(3); // [1, 3, 2] //q.pushMiddle(4); // [1, 4, 3, 2] //q.popFront(); // return 1 -> [4, 3, 2] //q.popMiddle(); // return 3 -> [4, 2] //q.popMiddle(); // return 4 -> [2] //q.popBack(); // return 2 -> [] //q.popFront(); // return -1 -> [] (The queue is empty) // // Constraints: // 1 <= val <= 109 // At most 1000 calls will be made to pushFront, pushMiddle, pushBack, popFront, // popMiddle, and popBack. // // Related Topics 设计 链表 // 👍 6 👎 0
//leetcode submit region begin(Prohibit modification and deletion) classFrontMiddleBackQueue{ private Deque<Integer> left; private Deque<Integer> right;
publicFrontMiddleBackQueue(){ left = new LinkedList<>(); right = new LinkedList<>(); }
publicintpopFront(){ if (left.size() + right.size() == 0) { return -1; } Integer v; if (left.size() == 0) { v = right.pollFirst(); }else { v= left.pollFirst(); } balanceQueue(); return v == null ? -1: v; }
publicintpopMiddle(){ if (left.size() + right.size() == 0) { return -1; } Integer v = left.pollLast(); balanceQueue(); return v == null ? -1: v; }
publicintpopBack(){ if (left.size() + right.size() == 0) { return -1; } Integer v; if (right.size() == 0) { v = left.pollLast(); } else { v = right.pollLast(); } balanceQueue(); return v == null ? -1: v; }
privatevoidbalanceQueue(){ if (left.size() - right.size() >=2) { right.addFirst(left.pollLast()); } if (left.size() < right.size()) { left.addLast(right.pollFirst()); } } } /** * Your FrontMiddleBackQueue object will be instantiated and called as such: * FrontMiddleBackQueue obj = new FrontMiddleBackQueue(); * obj.pushFront(val); * obj.pushMiddle(val); * obj.pushBack(val); * int param_4 = obj.popFront(); * int param_5 = obj.popMiddle(); * int param_6 = obj.popBack(); */ //leetcode submit region end(Prohibit modification and deletion) }
func(this *FrontMiddleBackQueue)PopFront()int { v := -1 if this.isEmpty() { return v } if this.lQueue.count == 0 { v = this.rQueue.popFront() } else { v = this.lQueue.popFront() } this.formatQueue()
return v }
func(this *FrontMiddleBackQueue)PopMiddle()int { v := -1 if this.isEmpty() { return v } v = this.lQueue.popTail() this.formatQueue()
return v }
func(this *FrontMiddleBackQueue)PopBack()int { v := -1 if this.isEmpty() { return v } if this.rQueue.count == 0 { v = this.lQueue.popTail() } else { v = this.rQueue.popTail() } this.formatQueue()
publicclassNumberOfRecentCalls{ publicstaticvoidmain(String[] args){ Solution s = new NumberOfRecentCalls().new Solution(); }
//You have a RecentCounter class which counts the number of recent requests with in a certain time frame. // Implement the RecentCounter class: // RecentCounter() Initializes the counter with zero recent requests. // int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number // of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the // number of requests that have happened in the inclusive range [t - 3000, t]. // // It is guaranteed that every call to ping uses a strictly larger value of t than the previous call. // // Example 1: //Input //["RecentCounter", "ping", "ping", "ping", "ping"] //[[], [1], [100], [3001], [3002]] //Output //[null, 1, 2, 3, 3] // //Explanation //RecentCounter recentCounter = new RecentCounter(); //recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1 //recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2 //recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3 //recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3 // Constraints: // 1 <= t <= 109 // Each test case will call ping with strictly increasing values of t. // At most 104 calls will be made to ping. // // Related Topics 队列 // 👍 82 👎 0
//leetcode submit region begin(Prohibit modification and deletion) classRecentCounter{ private Deque<Integer> deque = new LinkedList();
/** * Your RecentCounter object will be instantiated and called as such: * RecentCounter obj = new RecentCounter(); * int param_1 = obj.ping(t); */ //leetcode submit region end(Prohibit modification and deletion) }
给你一个用字符数组 tasks 表示的 CPU 需要执行的任务列表。其中每个字母表示一种不同种类的任务。任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完。在任何一个单位时间,CPU 可以完成一个任务,或者处于待命状态。
然而,两个 相同种类 的任务之间必须有长度为整数 n 的冷却时间,因此至少有连续 n 个单位时间内 CPU 在执行不同的任务,或者在待命状态。
你需要计算完成所有任务所需要的 最短时间 。
示例 1:
1 2 3 4
输入:tasks = ["A","A","A","B","B","B"], n = 2 输出:8 解释:A -> B -> (待命) -> A -> B -> (待命) -> A -> B 在本示例中,两个相同类型任务之间必须间隔长度为 n = 2 的冷却时间,而执行一个任务只需要一个单位时间,所以中间出现了(待命)状态。
示例 2:
1 2 3 4 5 6 7 8
输入:tasks = ["A","A","A","B","B","B"], n = 0 输出:6 解释:在这种情况下,任何大小为 6 的排列都可以满足要求,因为 n = 0 ["A","A","A","B","B","B"] ["A","B","A","B","A","B"] ["B","B","B","A","A","A"] ... 诸如此类
示例 3:
1 2 3 4
输入:tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2 输出:16 解释:一种可能的解决方案是: A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> (待命) ->(待命) -> A -> (待命) ->(待命) -> A