| | 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 | | namespace LeetCode.Algorithms.ThreeSum; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class ThreeSumTwoPointers : IThreeSum |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n^2) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public IList<IList<int>> ThreeSum(int[] nums) |
| 5 | 24 | | { |
| 5 | 25 | | if (nums.Length < 3) |
| 0 | 26 | | { |
| 0 | 27 | | return new List<IList<int>>(); |
| | 28 | | } |
| | 29 | |
|
| 5 | 30 | | Array.Sort(nums); |
| | 31 | |
|
| 5 | 32 | | List<IList<int>> result = []; |
| | 33 | |
|
| 36 | 34 | | for (var i = 0; i < nums.Length - 2; i++) |
| 13 | 35 | | { |
| 13 | 36 | | if (i > 0 && nums[i] == nums[i - 1]) |
| 1 | 37 | | { |
| 1 | 38 | | continue; |
| | 39 | | } |
| | 40 | |
|
| 12 | 41 | | var left = i + 1; |
| 12 | 42 | | var right = nums.Length - 1; |
| | 43 | |
|
| 34 | 44 | | while (left < right) |
| 22 | 45 | | { |
| 22 | 46 | | var sum = nums[i] + nums[left] + nums[right]; |
| | 47 | |
|
| 22 | 48 | | switch (sum) |
| | 49 | | { |
| | 50 | | case 0: |
| 8 | 51 | | result.Add(new List<int> { nums[i], nums[left], nums[right] }); |
| | 52 | |
|
| 11 | 53 | | while (left < right && nums[left] == nums[left + 1]) |
| 3 | 54 | | { |
| 3 | 55 | | left++; |
| 3 | 56 | | } |
| | 57 | |
|
| 8 | 58 | | while (left < right && nums[right] == nums[right - 1]) |
| 0 | 59 | | { |
| 0 | 60 | | right--; |
| 0 | 61 | | } |
| | 62 | |
|
| 8 | 63 | | left++; |
| 8 | 64 | | right--; |
| | 65 | |
|
| 8 | 66 | | break; |
| | 67 | | case < 0: |
| 5 | 68 | | left++; |
| 5 | 69 | | break; |
| | 70 | | default: |
| 9 | 71 | | right--; |
| 9 | 72 | | break; |
| | 73 | | } |
| 22 | 74 | | } |
| 12 | 75 | | } |
| | 76 | |
|
| 5 | 77 | | return result; |
| 5 | 78 | | } |
| | 79 | | } |