//*********************************//反转字符
Test Date:Console.WriteLine("abcdef")
Console.WriteLine(Reverse3("Iam a Girl"));
Console.ReadKey();
//*********************************
public static string Reverse3(string ori)
{
ori = ori.Trim();
if (string.IsNullOrEmpty(ori))
{
return null;
}
try
{
StringBuilder Sb = new StringBuilder(ori.Length);
if (ori.Contains(' '))
{
string[] array =ori.Split(' ');
for (int i = array.Length - 1; i>= 0; i--)
{
Sb.Append(array[i] + ' ');
}
}
else
{
for (int i = ori.Length - 1; i >=0; i--)
{
Sb.Append(ori[i]);
}
}
return Sb.ToString();
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
//*********************************
public static void Reverse(string str)
{
string m = "";
for (int i = str.Length - 1; i>=0; i--)
{
m += str[i];
}
Console.WriteLine(m);
Console.ReadKey();
}
public static string Reverse1(string str)
{
string[] SStr = str.Split(' ');
string NewStr = "";
for (int i = SStr.Length-1; i >= 0;i--)
{
NewStr += SStr[i]+' ';
}
return NewStr;
}
//*********************************最大最小值
#region Max or min in Array
public static int FindMax(int[] a)
{
int max=a[0];
for (int i = 0; i < a.Length; i++)
{
if(a[i]>max)
{
max = a[i];
}
}
return max;
}
public static int FindMin(int[] a)
{
int min=a[0];
for(int j=0;j<a.Length;j++)
{
if(a[j]<min)
{
min=a[j];
}
}
return min;
}
#endregion
//*********************************找出数组中出现次数超过一半(出现次数最多)的元素
分析
设置一个当前值和当前值的计数器,初始化当前值为数组首元素,计数器值为1,然后从第二个元素开始遍历整个数组,对于每个被遍历到的值a[i]
1 如果a[i]==currentValue,则计数器值加1
2 如果a[i] != currentValue, 则计数器值减1,如果计数器值小于0,则更新当前值为a[i],并将计数器值重置为1
代码
#regionFind Element
public static int FindElement(int[] a)
{
int curValue = a[0];
int count = 1;
for (int i = 1; i < a.Length;++i)
{
if (a[i] == curValue)
{
count++;
}
else
{
count--;
if (count < 0)
{
curValue = a[i];
count = 1;
}
}
}
return curValue;
}
#endregion
另一个方法是先对数组排序,然后取中间元素即可,因为如果某个元素的个数超过一半,那么数组排序后该元素必定占据数组的中间位置。
//*********************************数组相同元素(先给数组排序再遍历||=||>||<)
TestDate:
int[] A = { 1,2,3,4,5,10,5};
int[] B = { 1,2,3,5,6,7,8,9,10};
Console.WriteLine(FindElement(A,B));
#region Find the common element in two array
public static void FindElement(int[] a, int[] b)
{
int i = 0;
int j = 0;
while(i<a.Length&&j<b.Length)
{
if(a[i]<b[j])
{
i++;
}
else if (a[i] == b[j])
{
Console.WriteLine(a[i]);
i++;
j++;
}
else if(a[i]>b[j])
{
j++;
}
}
}
#endregion
//*********************************数组求和一句话(递归)
#region Sum of Array
public static int Sum(int[] a, int n)
{
return n == 0 ? 0 : Sum(a, n - 1) + a[n - 1];
}
#endregion
//*********************************Bubble排序
#region Sorting
public static int[] bubbleSort(int[] a)
{
for (int i = 0; i < a.Length; i++)
{
for (int j = i + 1; j < a.Length;j++ )
{
if (a[i] < a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a;
}
#endregion