CSharp 二个数组求交集 源代码
时间: 2024-02-16 07:49:48 浏览: 21
int[] arr1 = { 1, 2, 3, 4, 5 };
int[] arr2 = { 3, 4, 5, 6, 7 };
List<int> intersect = new List<int>();
foreach (int num in arr1)
{
if (arr2.Contains(num))
{
intersect.Add(num);
}
}
Console.WriteLine("The intersection of the two arrays is:");
foreach (int num in intersect)
{
Console.Write(num + " ");
}
相关问题
CSharp 实现动态数组 源代码
Sure, I can help you with that. Here's a sample C# code for implementing a dynamic array:
```
using System;
class DynamicArray<T>
{
private T[] array;
private int size;
public DynamicArray(int capacity = 16)
{
array = new T[capacity];
size = 0;
}
public void Add(T item)
{
if (size == array.Length)
{
Array.Resize(ref array, array.Length * 2);
}
array[size++] = item;
}
public T Get(int index)
{
if (index < 0 || index >= size)
{
throw new IndexOutOfRangeException();
}
return array[index];
}
public int Size
{
get { return size; }
}
}
```
Hope that helps! Do you have any other questions?
CSharp 实现有序数组中查找数字的范围 源代码
请看以下C#源代码:
```csharp
public static int[] SearchRange(int[] nums, int target) {
int left = 0, right = nums.Length - 1;
int start = -1, end = -1;
// 找出数字范围的起始位置
while(left <= right) {
int mid = (left + right) / 2;
if(nums[mid] >= target) {
right = mid - 1;
if(nums[mid] == target) {
start = mid;
}
} else {
left = mid + 1;
}
}
// 如果数组中没有目标数字,直接返回[-1, -1]
if(start == -1) {
return new int[]{-1, -1};
}
// 找出数字范围的结束位置
left = start;
right = nums.Length - 1;
while(left <= right) {
int mid = (left + right) / 2;
if(nums[mid] <= target) {
left = mid + 1;
if(nums[mid] == target) {
end = mid;
}
} else {
right = mid - 1;
}
}
return new int[]{start, end};
}
```
这段代码实现了在有序数组中查找数字的范围,可以找出目标数字在数组中出现的起始位置和结束位置。