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