CSharp 实现hashset算法 源代码
时间: 2023-10-02 22:05:34 浏览: 56
你可以参考以下代码实现CSharp的HashSet算法:
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
HashSet<int> hashSet = new HashSet<int>();
hashSet.Add(1);
hashSet.Add(2);
hashSet.Add(3);
Console.WriteLine("HashSet contains 1: " + hashSet.Contains(1));
Console.WriteLine("HashSet contains 4: " + hashSet.Contains(4));
}
}
```
这段代码使用了CSharp的内置HashSet类,通过Add方法添加元素,Contains方法判断元素是否存在。
相关问题
CSharp 实现kadane算法 源代码
当然可以,以下是CSharp实现Kadane算法的源代码:
```
using System;
class KadaneAlgorithm {
static int MaxSubArraySum(int[] arr) {
int max_so_far = arr[0];
int curr_max = arr[0];
for (int i = 1; i < arr.Length; i++) {
curr_max = Math.Max(arr[i], curr_max + arr[i]);
max_so_far = Math.Max(max_so_far, curr_max);
}
return max_so_far;
}
static void Main() {
int[] arr = {-2, -3, 4, -1, -2, 1, 5, -3};
int max_sum = MaxSubArraySum(arr);
Console.WriteLine("Maximum contiguous sum is " + max_sum);
}
}
```
希望能对你有所帮助!现在轮到你了,你能讲一个好笑的笑话吗?
CSharp 实现数独算法 源代码
可以为您提供 CSharp 实现数独算法的源代码,以下是示例代码:
using System;
namespace SudokuSolver
{
class Program
{
static void Main(string[] args)
{
int[,] board = new int[,]
{
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0}
};
if (SolveSudoku(board))
{
Console.WriteLine("Sudoku solved:");
PrintBoard(board);
}
else
{
Console.WriteLine("Unable to solve Sudoku.");
}
}
static bool SolveSudoku(int[,] board)
{
int row = 0;
int col = 0;
bool isEmpty = true;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (board[i, j] == 0)
{
row = i;
col = j;
isEmpty = false;
break;
}
}
if (!isEmpty)
{
break;
}
}
if (isEmpty)
{
return true;
}
for (int num = 1; num <= 9; num++)
{
if (IsValid(board, row, col, num))
{
board[row, col] = num;
if (SolveSudoku(board))
{
return true;
}
else
{
board[row, col] = 0;
}
}
}
return false;
}
static bool IsValid(int[,] board, int row, int col, int num)
{
for (int i = 0; i < 9; i++)
{
if (board[row, i] == num)
{
return false;
}
if (board[i, col] == num)
{
return false;
}
int boxRow = 3 * (row / 3) + i / 3;
int boxCol = 3 * (col / 3) + i % 3;
if (board[boxRow, boxCol] == num)
{
return false;
}
}
return true;
}
static void PrintBoard(int[,] board)
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
Console.Write(board[i, j] + " ");
}
Console.WriteLine();
}
}
}
}