| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | using LeetCode.Core.Models; |
| | 13 | |
|
| | 14 | | namespace LeetCode.Algorithms.InsertGreatestCommonDivisorsInLinkedList; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class InsertGreatestCommonDivisorsInLinkedListSimulation : IInsertGreatestCommonDivisorsInLinkedList |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n * log min(a,b)) |
| | 21 | | /// Space complexity - O(n) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="head"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public ListNode? InsertGreatestCommonDivisors(ListNode head) |
| 2 | 26 | | { |
| 2 | 27 | | var dummyHead = new ListNode(0, head); |
| | 28 | |
|
| 2 | 29 | | var previousNode = head; |
| 2 | 30 | | var currentNode = head.next; |
| | 31 | |
|
| 5 | 32 | | while (currentNode != null) |
| 3 | 33 | | { |
| 3 | 34 | | var greatestCommonDivisor = GetGreatestCommonDivisor(previousNode.val, currentNode.val); |
| | 35 | |
|
| 3 | 36 | | previousNode.next = new ListNode(greatestCommonDivisor, currentNode); |
| | 37 | |
|
| 3 | 38 | | previousNode = currentNode; |
| 3 | 39 | | currentNode = currentNode.next; |
| 3 | 40 | | } |
| | 41 | |
|
| 2 | 42 | | return dummyHead.next; |
| 2 | 43 | | } |
| | 44 | |
|
| | 45 | | private static int GetGreatestCommonDivisor(int a, int b) |
| 3 | 46 | | { |
| 10 | 47 | | while (b != 0) |
| 7 | 48 | | { |
| 7 | 49 | | var temp = a % b; |
| 7 | 50 | | a = b; |
| 7 | 51 | | b = temp; |
| 7 | 52 | | } |
| | 53 | |
|
| 3 | 54 | | return a; |
| 3 | 55 | | } |
| | 56 | | } |