mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 0018.四数之和 C#版本
This commit is contained in:
@ -403,5 +403,67 @@ func fourSum(_ nums: [Int], _ target: Int) -> [[Int]] {
|
||||
}
|
||||
```
|
||||
|
||||
C#:
|
||||
```csharp
|
||||
public class Solution
|
||||
{
|
||||
public IList<IList<int>> FourSum(int[] nums, int target)
|
||||
{
|
||||
var result = new List<IList<int>>();
|
||||
|
||||
Array.Sort(nums);
|
||||
|
||||
for (int i = 0; i < nums.Length - 3; i++)
|
||||
{
|
||||
int n1 = nums[i];
|
||||
if (i > 0 && n1 == nums[i - 1])
|
||||
continue;
|
||||
|
||||
for (int j = i + 1; j < nums.Length - 2; j++)
|
||||
{
|
||||
int n2 = nums[j];
|
||||
if (j > i + 1 && n2 == nums[j - 1])
|
||||
continue;
|
||||
|
||||
int left = j + 1;
|
||||
int right = nums.Length - 1;
|
||||
|
||||
while (left < right)
|
||||
{
|
||||
int n3 = nums[left];
|
||||
int n4 = nums[right];
|
||||
int sum = n1 + n2 + n3 + n4;
|
||||
|
||||
if (sum > target)
|
||||
{
|
||||
right--;
|
||||
}
|
||||
else if (sum < target)
|
||||
{
|
||||
left++;
|
||||
}
|
||||
else
|
||||
{
|
||||
result.Add(new List<int> { n1, n2, n3, n4 });
|
||||
|
||||
while (left < right && nums[left] == n3)
|
||||
{
|
||||
left++;
|
||||
}
|
||||
|
||||
while (left < right && nums[right] == n4)
|
||||
{
|
||||
right--;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user