笔试常用代码(2023-04-03)
快速排序
static void Main(string[] args)
{
int[] arr = new int[]{3,42,5,2,3,53,5,32};
quickSort(arr, 0, arr.Length-1);
}
Public static void quickSort(int[] arr, int lo, int hi)
{
if(hi <= lo)
return;
int j = partition(int[] arr, int i, int j);
quick(arr, lo, j-1);
quikc(arr, j+1, hi);
}
Private static int partition(int[] arr, int lo, int hi)
{
int i = lo, j = hi+1;
int v = arr[lo];
while(true){
while(arr[++i] < v)
if( i == hi)
break;
while(v < arr[--j])
if( i == lo)
break;
if(i >= j)
break;
each(arr, i, j);
}
each(arr, lo, j);
return j;
}
Private static void exch(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
字符串替代
实现接口Replace strA.Replace(strB, strC)
Public static void Main(String[] args){
}
Public static string myReplace(string original, string oldValue, string newValue)
{
char[] strA = original.ToCharArray();
char[] strB = oldValue.ToCharArray();
char[] strC = newValue.ToCharArray();
int n = original.Length, m = oldValue.Length;
if(m == 0)
return original;
int[] pi = new int[m];
for(int i = 1; j =0; i < m; i++)
{
if(j > 0 && strB[i] != strB[j])
j = pi[j -1];
if(strB[i] == strB[j])
j++;
pi[i] = j;
}
for(int i = 0; j =0; i < n; i++)
{
if(j > 0 && strA[i] != strB[j])
j = pi[j -1];
if(strA[i] == strB[j])
j++;
if(j == m){ //交换目标 位置 i - m + 1
}
}
return XXX;
}
数组转置
1 2
3 4
5 6
转置:
1 3 5
2 4 6
Public static int[,] transpos(int[,] matrix)
{
int m = matrix.GetLength(0), n = matrix.GetLength(1);
int[,] trans = new int[n , m];
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
trans[j, i] = matrix[i, j];
}
}
return trans;
}
100内10个随机数
public static void InsertRandomArray()
{
List<int> list = new List<int>();
Random rd = new Random();
while(list.Count < 10)
{
int temp = rd.Next(1, 101);
if(!list.Contains(temp)
list.Add(temp);
}
}