mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 0015.三数之和 C#版本
This commit is contained in:
@ -509,5 +509,64 @@ int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
C#:
|
||||||
|
```csharp
|
||||||
|
public class Solution
|
||||||
|
{
|
||||||
|
public IList<IList<int>> ThreeSum(int[] nums)
|
||||||
|
{
|
||||||
|
var result = new List<IList<int>>();
|
||||||
|
|
||||||
|
Array.Sort(nums);
|
||||||
|
|
||||||
|
for (int i = 0; i < nums.Length - 2; i++)
|
||||||
|
{
|
||||||
|
int n1 = nums[i];
|
||||||
|
|
||||||
|
if (n1 > 0)
|
||||||
|
break;
|
||||||
|
|
||||||
|
if (i > 0 && n1 == nums[i - 1])
|
||||||
|
continue;
|
||||||
|
|
||||||
|
int left = i + 1;
|
||||||
|
int right = nums.Length - 1;
|
||||||
|
|
||||||
|
while (left < right)
|
||||||
|
{
|
||||||
|
int n2 = nums[left];
|
||||||
|
int n3 = nums[right];
|
||||||
|
int sum = n1 + n2 + n3;
|
||||||
|
|
||||||
|
if (sum > 0)
|
||||||
|
{
|
||||||
|
right--;
|
||||||
|
}
|
||||||
|
else if (sum < 0)
|
||||||
|
{
|
||||||
|
left++;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
result.Add(new List<int> { n1, n2, n3 });
|
||||||
|
|
||||||
|
while (left < right && nums[left] == n2)
|
||||||
|
{
|
||||||
|
left++;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (left < right && nums[right] == n3)
|
||||||
|
{
|
||||||
|
right--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
<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