| | 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.DeleteNodeFromLinkedListPresentInArray; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class DeleteNodeFromLinkedListPresentInArrayBinarySearch : IDeleteNodeFromLinkedListPresentInArray |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n log n + m log n) |
| | 21 | | /// Space complexity - O(1) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="nums"></param> |
| | 24 | | /// <param name="head"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public ListNode? ModifiedList(int[] nums, ListNode? head) |
| 5 | 27 | | { |
| 5 | 28 | | if (nums.Length == 0) |
| 1 | 29 | | { |
| 1 | 30 | | return head; |
| | 31 | | } |
| | 32 | |
|
| 4 | 33 | | Array.Sort(nums); |
| | 34 | |
|
| 4 | 35 | | var dummyHead = new ListNode(0, head); |
| | 36 | |
|
| 4 | 37 | | var node = dummyHead; |
| | 38 | |
|
| 45 | 39 | | while (node?.next != null) |
| 41 | 40 | | { |
| 41 | 41 | | if (BinarySearch(nums, node.next.val)) |
| 21 | 42 | | { |
| 21 | 43 | | node.next = node.next.next; |
| 21 | 44 | | } |
| | 45 | | else |
| 20 | 46 | | { |
| 20 | 47 | | node = node.next; |
| 20 | 48 | | } |
| 41 | 49 | | } |
| | 50 | |
|
| 4 | 51 | | return dummyHead.next; |
| 5 | 52 | | } |
| | 53 | |
|
| | 54 | | private static bool BinarySearch(int[] nums, int target) |
| 41 | 55 | | { |
| 41 | 56 | | var left = 0; |
| 41 | 57 | | var right = nums.Length - 1; |
| | 58 | |
|
| 132 | 59 | | while (left <= right) |
| 112 | 60 | | { |
| 112 | 61 | | var mid = left + ((right - left) / 2); |
| | 62 | |
|
| 112 | 63 | | if (nums[mid] == target) |
| 21 | 64 | | { |
| 21 | 65 | | return true; |
| | 66 | | } |
| | 67 | |
|
| 91 | 68 | | if (nums[mid] < target) |
| 45 | 69 | | { |
| 45 | 70 | | left = mid + 1; |
| 45 | 71 | | } |
| | 72 | | else |
| 46 | 73 | | { |
| 46 | 74 | | right = mid - 1; |
| 46 | 75 | | } |
| 91 | 76 | | } |
| | 77 | |
|
| 20 | 78 | | return false; |
| 41 | 79 | | } |
| | 80 | | } |