(C#)算法题
1. Convert string from "AAABBCC" to "A3B2C2".
当面试者提出这个问题的时候,首先需要确认题意:譬如:字符串是不是顺序的,是否有字符重复出现。
例如: ABBAACB , AAABBCCCBBAA。
如果是顺序的话可以一次遍历字符,如果是杂序的话,需要2次遍历。
C#里面采用Dictionary是很方便的。
public static string CountCharNumber(string input)
{
Dictionary<char, int> converted = new Dictionary<char, int>();
foreach (var ch in input)
{
// If it is the new char(key), then add into the dictionary.
if (!converted.ContainKey(ch))
{
converted.Add(ch, );
} converted[ch]++;
} StringBuilder output = new StringBuilder(); foreach(var data in converted)
{
output.Append(data.Key).Append(data.Value);
} return output.ToString();
}
2. 如何判断一个数是2 的N次方。
方法一: 转换为2进制,第一位为1.
方法二: 如果这个数是2的N次方,那么符合如下条件: num & (num - 1) == 0;
3. 一个小女孩正在用左手手指数数,从1数到n。她从拇指算作1开始数起,然后,食指为2,中指为3,无名指为4,小指为5。接下来调转方向,无名指算作6,中指为7,食指为8,大拇指为9,如此反复。问最后会停在那个手指上?用编号1、2、3、4、5依次表示大拇指、食指、中指、无名指、小指。 输入格式: 输入多组数据。每组数据占一行,只包含一个整数n.
思路:因为大拇指、无名指不重复,所以以手指正向1-4,反向5-2为整数计算就是8个手指头,也就是以大拇指为重复计数开始一轮为8个手指。只要你输入的数除以8,剩下的余数按1-4,5-8去判断就知道停留在哪个手指了。
建立了Dictionary<int, string> (), key 为0 到 7, 输入的数%8 取yu'数,然后查表。
4. 用C#实现返回一个字符串的字符所有组合,输入的字符串中字符不能有重复。如输入"ABC",返回{"ABC","ACB","BAC","BCA"...},输入WXYZ,返回{"WXYZ","WYXZ","WYZX"...}.
思路: 用递归算法: 公式: 新字符串= 插入新的字符到 之前的字符串的任何一个位置。
result.Add(child.Insert(i, current.ToString()));
5.题目:输入一个整形数组,数组里有正数也有负数。数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。求所有子数组的和的最大值。要求时间复杂度为O(n)。
例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18。
思路: 当我们加上一个正数时,和会增加;当我们加上一个负数时,和会减少。如果当前得到的和是个负数,那么这个和在接下来的累加中应该抛弃并重新清零,不然的话这个负数将会减少接下来的和。如果数组里面所有的数字都是小于0, 那么选取最大的一个即可。
6.题目:在数组中,数字减去它右边的数字得到一个数对之差。求所有数对之差的最大值。例如在数组{2, 4, 1, 16, 7, 5, 11, 9}中,数对之差的最大值是11,是16减去5的结果。
思路: 二分法 + 递归。
数对之差的最大值只有可能是下面三种情况之一:(1)被减数和减数都在第一个子数组中,即第一个子数组中的数对之差的最大值;(2)被减数和减数都在第二个子数组中,即第二个子数组中数对之差的最大值;(3)被减数在第一个子数组中,是第一个子数组的最大值。减数在第二个子数组中,是第二个子数组的最小值。这三个差值的最大者就是整个数组中数对之差的最大值。
情况(1),(2) 又可以使用(1)(2)(3) 方法来解决。
Convert string "123" to number 123.
思路: 首先提出的应该是用
int.Parse(str);
int.TryParse(string, out intResult);
来回答。
然后用基本的算法:
public static int ConvertStrToNum(string input)
{
int output = ;
if (String.IsNullOrEmpty(input))
{
// throw new exception();
} char[] charArray = input.ToCharArray();
for(int i = ; i < charArray.Length; i++)
{
if ((charArray[i] - '') >= && (charArray[i] - '')<=)
{
output = output * + (charArray[i] - '');
}
else
{
//throw new exception();
}
}
return output;
}
Check whether a given point lies inside of a triangle or not.
思路: 给出一个求三角形ABC面积的公式,然后判断条件是: PAB + PBC + PCA = ABC 面积 即为内。
面试的时候可能还要先判断 A,B,C 三点是否一定构成三角形。
注意,设A点为(x1, y1), B点为(x2, y2), C点位(x3, y3). 那么三角形面积为: 1/2[(x1y2-x2y1)+(x2y3-x3y2)+(x3y1-x1y3)].
Matching Nuts & Bolts Problem. (or Lock & Key problem)
思路1:暴力匹配 O(n^2)
思路2: 先快排序,然后从左开始同时扫描Nuts数组和Bolts数组。进行匹配。 O(nlogn).
Given an array of ints, write a C# method to total all the values that are even numbers.
1. LINQ
static int sumEvenNumber(int[] numbers)
{
return numbers.Where(i => i % == ).Sum();
}
2. Normal.
static int sumEvenNumber1(int[] numbers)
{
int sumEven = ;
for (int i = ; i < numbers.Length; i++)
{
if (numbers[i] % == )
{
sumEven += numbers[i];
}
} return sumEven;
}
注意:If considering the overflow, using long data type is better.
static long TotalAllEvenNumbers(int[] intArray) {
return intArray.Where(i => i % 2 == 0).Sum(i => (long)i);
}
What is the output of the short program below? Explain your answer.
class Program {
static String location;
static DateTime time;
static void Main() {
Console.WriteLine(location == null ? "location is null" : location);
Console.WriteLine(time == null ? "time is null" : time.ToString());
}
}
The output will be:
location is null
1/1/0001 12:00:00 AM
Although both variables are uninitialized, String
is a reference type and DateTime
is a value type. As a value type, an unitialized DateTime
variable is set to a default value of midnight of 1/1/1 (yup, that’s the year 1 A.D.), not null
.
What is the output of the program below? Explain your answer.
delegate void Printer();
static void Main()
{
List printers = new List();
for (int i = 0; i < 10; i++)
{
printers.Add(delegate { Console.WriteLine(i); });
}
foreach (var printer in printers)
{
printer();
}
}
This program will output the number 10 ten times.
Here’s why: The delegate is added in the for loop and “reference” (or perhaps “pointer” would be a better choice of words) to i
is stored, rather than the value itself. Therefore, after we exit the loop, the variable i
has been set to 10, so by the time each delegate is invoked, the value passed to all of them is 10.
猫叫了,老鼠跑了,主人醒了。
解题: Publisher-Subscriber design pattern. Using event and event handler is the best method.
// Publisher - Cat
public class Cat
{
public event EventHandler ScreamEventHandler; public void RaiseScreamEvent()
{
Console.WriteLine("Cat is screaming...");
if (this.ScreamEventHandler!= null)
{
this.ScreamEventHandler(this, null);
}
}
}
// Subscribers.
public class Subscriber
{
private Cat myCat;
public Subscriber(Cat cat)
{
this.myCat = cat;
this.myCat.ScreamEventHandler += this.Action;
} public virtual void Action(object o, EventArgs e)
{
Console.WriteLine("Starting action....");
}
} public class Mouse : Subscriber
{
public Mouse(Cat cat): base(cat)
{
}
public override void Action(object o, EventArgs e)
{
Console.WriteLine("Mouse is escaping...");
}
} public class Host : Subscriber
{
public Host(Cat cat): base(cat)
{ }
public override void Action(object o, EventArgs e)
{
Console.WriteLine("Host is waken up...");
}
}
Given a string s, return all the palindromic permutationns (without duplicates) of it. Retrun an empty array if no palindromic combinations can be formed.
思路: 暴力匹配
public string[] GetAllPalindromicPermutation(string input)
{
List<string> palindromics = new List<string>();
string subStr = string.Empty;
for (int i = ; i < input.Length - ; i++)
{
for (int strLen = ; strLen <= input.Length; strLen++)
{
if (i + strLen <= input.Length)
{
subStr = input.Substring(i, strLen);
if (IsPalindromic(subStr) && !palindromics.Contains(subStr))
{
palindromics.Add(subStr);
}
}
}
} return palindromics.ToArray();
} private bool IsPalindromic(string str)
{
// Revert string.
Char[] chars = str.ToCharArray();
Array.Reverse(chars);
string reversedStr = new string(chars);
return str == reversedStr;
}
(C#)算法题的更多相关文章
- 一道java算法题分析
最近在面试中遇到这样的一道算法题: 求100!的结果的各位数之和为多少? 如:5!=5*4*3*2*1=120,那么他们的和为1+2+0=3这道题不算难,不过倒是注意的细节也有 ...
- FCC上的初级算法题
核心提示:FCC的算法题一共16道.跟之前简单到令人发指的基础题目相比,难度是上了一个台阶.主要涉及初步的字符串,数组等运算.仍然属于基础的基础,官方网站给出的建议完成时间为50小时,超出了之前所有非 ...
- 解决一道leetcode算法题的曲折过程及引发的思考
写在前面 本题实际解题过程是 从 40秒 --> 24秒 -->1.5秒 --> 715ms --> 320ms --> 48ms --> 36ms --> ...
- js 中的算法题,那些经常看到的
js中遇到的算法题不是很多,可以说基本遇不到.但面试的时候,尤其是一些大公司,总是会出这样那样的算法题,考察一个程序员的逻辑思维能力.如下: 1.回文. 回文是指把相同的词汇或句子,在下文中调换位置或 ...
- JavaScript算法题之–随机数的生成
JavaScript算法题之–随机数的生成 需求描述:从一组有序的数据中生成一组随机并且不重复的数,类似于简单的抽奖程序的实现. 先来生成一个有序的数组: 1 var arr = [], 2 ...
- 简单的算法题, Find Minimum in Rotated Sorted Array 的Python实现。
简单的算法题, Find Minimum in Rotated Sorted Array 的Python实现. 题目: Suppose a sorted array is rotated at som ...
- 经典算法题每日演练——第十七题 Dijkstra算法
原文:经典算法题每日演练--第十七题 Dijkstra算法 或许在生活中,经常会碰到针对某一个问题,在众多的限制条件下,如何去寻找一个最优解?可能大家想到了很多诸如“线性规划”,“动态规划” 这些经典 ...
- 经典算法题每日演练——第十六题 Kruskal算法
原文:经典算法题每日演练--第十六题 Kruskal算法 这篇我们看看第二种生成树的Kruskal算法,这个算法的魅力在于我们可以打一下算法和数据结构的组合拳,很有意思的. 一:思想 若存在M={0, ...
- 经典算法题每日演练——第十四题 Prim算法
原文:经典算法题每日演练--第十四题 Prim算法 图论在数据结构中是非常有趣而复杂的,作为web码农的我,在实际开发中一直没有找到它的使用场景,不像树那样的频繁使用,不过还是准备 仔细的把图论全部过 ...
- 经典算法题每日演练——第十一题 Bitmap算法
原文:经典算法题每日演练--第十一题 Bitmap算法 在所有具有性能优化的数据结构中,我想大家使用最多的就是hash表,是的,在具有定位查找上具有O(1)的常量时间,多么的简洁优美, 但是在特定的场 ...
随机推荐
- MVC部署到iis
程序域功能->打开或关闭->iis信息服务及.net framework下的两个要勾选 1. 发布程序,以文件系统file system 的形式,发布到一个文件夹里 自定义-> ...
- jedis,spring-redis-data 整合使用,版本问题异常以及解决。
最近整合使用redis spring-redis 出现了一下问题 spring:3.2.4.RELEASE jedis: jedis 2.4.2 spring-data-redis: 1.5.2.R ...
- iOS开发UI篇—使用嵌套模型完成的一个简单汽车图标展示程序
iOS开发UI篇—使用嵌套模型完成的一个简单汽车图标展示程序 一.plist文件和项目结构图 说明:这是一个嵌套模型的示例 二.代码示例: YYcarsgroup.h文件代码: // // YYcar ...
- redis教程
windows下安装redis: http://jingyan.baidu.com/article/49ad8bce40174f5834d8fa24.html redis教程: http://www. ...
- C# 跨线程操作无效
提示此错误的原因就是控件由主线程创建,在另一个线程进行操作时就会被阻止,防止数据间随意篡改. 如果一定要跨线程作业,如进度条或状态显示等,基本有三种方法解决: 1.Control.CheckForIl ...
- 制作一个顶部图片可以拉伸放大缩小效果的tableViewHeader
最近负责公司项目个人中心的项目模块研发,首页是一个头部图片可以拉伸放大缩小效果的tableViewHeader,今天这个demo和教程我增加了模糊效果和头像缩小效果.具体效果如图: 如果这个效果是想要 ...
- 对比学习UIKit和AppKit -- ViewController
在iOS中ViewController的基类是UIViewController:Mac中ViewController的基类是NSViewController. Mac中ViewController父类 ...
- Umap2:开源USB host安全评估工具
Umap2是一款由NCC Group和Cisco SAS小组开发的.基于python的USB host安全评估工具. 它拥有第一版所支持的所有功能: umap2emulate:USB设备枚举 umap ...
- 使用PHP处理文本小技巧
PHP的Cli模式使用:http://www.php.net/manual/zh/features.commandline.php PHP命令行部分参数:-B 在处理 stdin 之前先执行 ...
- java.net.BindException: address already in use <null>:xxxx
linux下,tomcat突然关闭了,执行关闭(shutdown.sh)和启动(startup.sh)成功后,tomcat仍未运行,查看tomcat的catalina日志发现这样一个报错:java.n ...