LeetCode 708. Insert into a Cyclic Sorted List

原题链接在这里:https://leetcode.com/problems/insert-into-a-cyclic-sorted-list/

题目:

Given a node from a cyclic linked list which is sorted in ascending order, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be a reference to any single node in the list, and may not be necessarily the smallest value in the cyclic list.

If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the cyclic list should remain sorted.

If the list is empty (i.e., given node is null), you should create a new single cyclic list and return the reference to that single node. Otherwise, you should return the original given node.

The following example may help you understand the problem better:



In the figure above, there is a cyclic sorted list of three elements. You are given a reference to the node with value 3, and we need to insert 2 into the list.



The new node should insert between node 1 and node 3. After the insertion, the list should look like this, and we should still return node 3.

题解:

上升阶段找比前大比后小的位置. 拐点看看insertVal是不是最大或者最小值, 是就加在拐点位置.

如果转回head还没有找到说明一直是平的, 就加在head前面.

Time Complexity: O(n).

Space: O(1).

AC Java:

 1 /*
 2 // Definition for a Node.
 3 class Node {
 4     public int val;
 5     public Node next;
 6 
 7     public Node() {}
 8 
 9     public Node(int _val,Node _next) {
10         val = _val;
11         next = _next;
12     }
13 };
14 */
15 class Solution {
16     public Node insert(Node head, int insertVal) {
17         if(head == null){
18             head = new Node(insertVal, null);
19             head.next = head;
20             return head;
21         }
22         
23         Node cur = head;
24         while(true){
25             if(cur.val < cur.next.val){
26                 // 上升阶段找比前小比后大的位置
27                 if(cur.val<=insertVal && insertVal<=cur.next.val){
28                     cur.next = new Node(insertVal, cur.next);
29                     break;
30                 }
31             }else if(cur.val > cur.next.val){
32                 // 拐点,如果比前个还大大说明insertVal最大, 加在拐点位置
33                 // 如果比后个还小说明insertVal最小, 也加在拐点位置
34                 if(cur.val<=insertVal || insertVal<=cur.next.val){
35                     cur.next = new Node(insertVal, cur.next);
36                     break;
37                 }
38             }else{
39                 // 一直都是相等的点
40                 if(cur.next == head){
41                     cur.next = new Node(insertVal, head);
42                     break;
43                 }
44             }
45             
46             cur = cur.next;
47         }
48         
49         return head;
50     }
51 }

猜你喜欢

转载自www.cnblogs.com/Dylan-Java-NYC/p/10972122.html
今日推荐