今天介绍几种常见的算法,在面试中或许能派上用场
1.字符串倒转
//Reverse a string
public static string Reverse(string ori)
{
string MyOri = ori.Trim();
if(string.IsNullOrEmpty(MyOri))
{
Console.WriteLine("The string you input is null or empty");
return null;
}
try
{
StringBuilder sb = new StringBuilder(MyOri.Length);
if (MyOri.Contains(' '))
{
string[] Array = MyOri.Split(' '); for (int i = Array.Length - ; i >= ; i--)
{
sb.Append(Array[i]+' ');
}
}
else
{
for(int i=MyOri.Length-;i>=;i--)
{
sb.Append(MyOri[i]);
}
}
return sb.ToString();
}
catch (Exception ex)
{ throw new Exception(ex.ToString());
} }
2.获取数值中最大值
//Find the max value from int array
public static int FindMax(int[] A)
{
int max = A[];
for(int i=;i<=A.Length-;i++)
{
if(max<A[i])
{
max = A[i];
}
}
return max;
}
3.获取相同元素,从两个数组中.
//find common element from two int array
public static List<int> FindCommonElement(int[] A,int[] B)
{
int i = ;
int j = ;
List<int> a=new List<int> { };
while(i<A.Length&&j<B.Length)
{
if(A[i]<B[j])
{
i++;
}
else if(A[i]==B[j])
{
a.Add(A[i]);
i++;
j++; }
else if(A[i]>B[j])
{
j++;
}
}
return a.ToList();
}
4.移除两数组中相同元素
public static List<int> RemoveSameElement(List<int> A, List<int> B)
{
List<int> C1 = new List<int>();
List<int> C2 = new List<int>();
for (int i = 0; i <=A.Count()-1; i++)
{
for (int j = 0; j <=B.Count() - 1; j++)
{
if (A[i] == B[j])
{
C1.Add(A[i]);
} }
}
foreach(int item in C1)
{
A.Remove(item);
} C2 = A.Concat(B).ToList();
return C2;
}
5.找到出现次数最多的元素
//Find the element which appeard most time
public static int FindElement(int[] A)
{
//适用于重复元素连续一起的情况
//int currentValue = A[0];
//int counter = 1;
//for(int i=1;i<A.Length-1;i++)
//{
// if(currentValue==A[i])
// {
// counter++;
// }
// else
// {
// counter--;
// if(counter<0)
// {
// currentValue = A[i];
// }
// }
//}
//return currentValue; var res = from n in A
group n by n into g
orderby g.Count() descending
select g;
var gr = res.First();
return gr.First(); }
6.冒泡排序
//Bubble Sort
public static int[] BubbleSort(int[] A)
{
for(int i=;i<A.Length;i++)
{
for(int j=i+;j<A.Length;j++)
{
if(A[i]<A[j])
{
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
}
return A;
}
7.数组求和,一句话
public static int Sum(int[] a, int n)
{ return n == ? : Sum(a, n - ) + a[n - ]; }