算法面试题
1. C# 1到100,每三个数 ,取第三个数,直到输出最后一个数。
注释:比如1-100,第一次输出的数就是3,6,9,12,15,18.....99,第二次输出的就是9,18,27,36,45,....99,直到最后输出为一个数。
别人的写法:
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>();
InitList(list);
RemoveIt(ref list);
for (int i = 0; i < list.Count; i++)
Console.WriteLine(list[i]);
Console.ReadLine();
}
static void InitList(List<int> list)
{
for (int i = 1; i <= 100; i++)
list.Add(i);
}
static void RemoveIt(ref List<int> list)
{
List<int> result = new List<int>();
for (int i = 1; i <= list.Count; i++)
{
if (i % 3 == 0)
{
result.Add(list[i - 1]);
if (result.Count > 1) Console.Write(",");
Console.Write(list[i - 1]);
}
}
Console.WriteLine();
list = result;
if (list.Count >= 3) RemoveIt(ref list);
}
}
自己的写法:
class Program
{
static void Main(string[] args)
{
Dictionary<int, int> dic = new Dictionary<int, int>();
for (int i = 1; i < 101; i++)
{
dic.Add(i, i);
}
while (true)
{
dic = run(dic);
if (dic.Count == 1)
{
break;
}
}
Console.ReadKey();
}
private static Dictionary<int, int> run(Dictionary<int, int> num)
{
int count = 0;
int dicIndex = 1;
Dictionary<int, int> dic = new Dictionary<int, int>();
foreach (var item in num)
{
count++;
if (count == 3)
{
count = 0;
dic.Add(dicIndex, item.Value);
dicIndex++;
}
}
//打印验证数据准确性
foreach (var item in dic)
{
Console.WriteLine(item.Key + ":" + item.Value);
}
Console.WriteLine("\r\n");
return dic;
}
}
2.54张牌洗牌算法:
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[54];
int length = numbers.Length;
for (int i = 0; i < length; i++)
{
numbers[i] = i + 1;
}
random(numbers, length);
foreach (int i in numbers)
{
Console.Write(i + " ");
}
Console.ReadKey();
}
private static void random(int[] array, int length)
{
int index;
int value;
for (int i = length - 1; i > 0; i--)
{
index = new Random().Next(0, i + 1);
value = array[i];
array[i] = array[index];
array[index] = value;
}
}
}
3.数据由小到大排序
一般的算法
int[] nums = new int[] { 56, 2, 65, 36, 21, 3, 5, 4, 6, 54, 88 };
for (int i = 0; i < nums.Length - 1; i++)
{
for (int j = 0; j < nums.Length - 1 - i; j++)
{
if (nums[j] > nums[j + 1])
{
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
foreach (var n in nums)
{
Console.WriteLine(n);
}
Console.ReadKey();
用Linq也可以实现
int[] nums = new int[] { 56, 2, 65, 36, 21, 3, 5, 4, 6, 54, 88 };
var result = from c in nums.ToList()
orderby c
select c;
foreach (var n in result)
{
Console.WriteLine(n);
}
Console.ReadKey();
以上两种最终实现的效果一样。
个人主要研究:金融系统、MIS系统、人力资源管理系统、数据采集系统、权限管理系统等等系统。主攻C#开发语言,Oracle、Sql Server,WCF和Remoting通信。
如需联系可加QQ:442389681 Email:lxc880615@163.com 手机:18922735098
QQ群交流:186841119 (请注明来自博客园)
博客园地址:http://www.cnblogs.com/jara/ http://www.cnblogs.com/luoyuhao/
提示:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果觉得还有帮助的话,可以点一下右下角的【推荐】,希望能够持续的为大家带来好的技术文章!想跟我一起进步么?那就【关注】我吧。
如果对文章有任何问题,都可以在评论中留言,我会尽可能的答复您,谢谢您的阅读

浙公网安备 33010602011771号