面试题2:单例模式
class SingleTon
{
public SingleTon Instance()
{
return Nested.instance;
}
private class Nested
{
internal static readonly SingleTon instance = new SingleTon();
}
}
要点:静态变量/函数只会在程序运行时执行一次。
面试题3:找出数组中重复的数字
public void Problem3()
{
HashSet<int> result = new HashSet<int>();
int[] input = {2,6,5,7,1,2,3,4,8};
for (int i = 0; i < input.Length; i++)
{
int value = input[i];
while (input[i] != i)
{
if (input[value] != value)
{
int temp = input[i];
input[i] = input[value];
input[value] = temp;
value = input[i];
}
else
{
result.Add(value);
break;
}
}
}
foreach (int value in result)
{
Console.WriteLine(value);
}
}
面试题3-2:在不改动原数组的前提下,找出重复的数字
public void Problem3_2()
{
int? result = null;
int num = 0;
int[] array = { 2, 3, 5, 4, 3, 2, 6, 7 };
int start = 0, end = array.Length - 1;
while (end >= start)
{
int mid = (end - start)>>1 + start;
int count = GetCount(array, start, mid);
if (end == start)
{
if (count > 1)
{
result = array[start];
num = count;
}
break;
}
if (count > (mid - start + 1))
{
end = mid;
}
else
{
start = mid + 1;
}
}
if (result == null)
{
Console.WriteLine("没有重复的数字");
}
else
{
Console.WriteLine(result + "重复了{0}次", num);
}
}
private int GetCount(int[] array, int start, int end)
{
int count = 0;
for (int i = 0; i < array.Length; i++)
{
for (int j = start; j <= end; j++)
{
if (array[i] == array[j])
{
count++;
}
}
}
return count;
}
面试题4:在二维数组中查找数字
public bool Problem4(int target)
{
int[,] input = {
{ 1,2,3},
{ 2,4,6},
{ 3,6,9},
};
bool result = false;
int col = input.GetUpperBound(0) + 1;
int row = input.GetLength(0);
//从右上开始遍历
int c = col - 1;//列
int r = 0;//行
while (c < 0 || r > row - 1)
{
int value = input[c, r];
if (value == target)
{
result = true;
break;
}
else if (value > target)
{
c--;
}
else
{
r++;
}
}
Console.WriteLine(result);
return result;
}
要点:从右上角或者左下角开始比较,才可以在每次比较中缩小查询的区域。
面试题5:将字符串中的空格提替换成指定字符
public string Problem5(string input, string target)
{
if (input.Length == 0)
{