(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, 0); 
                }

                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 = 0; 
            if (String.IsNullOrEmpty(input))
            {
               // throw new exception(); 
            }
    
            char[] charArray = input.ToCharArray(); 
            for(int i = 0; i < charArray.Length; i++)
            {
                if ((charArray[i] - '0') >=0 && (charArray[i] - '9')<=9)
                {
                    output = output * 10 + (charArray[i] - '0'); 
                }
                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 % 2 == 0).Sum(); 
        }

2. Normal.

        static int sumEvenNumber1(int[] numbers)
        {
            int sumEven = 0;
            for (int i = 0; i < numbers.Length; i++)
            {
                if (numbers[i] % 2 == 0)
                {
                    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 = 0; i < input.Length - 1; i++)
            {
                for (int strLen = 2; 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; 
        }
原文地址:https://www.cnblogs.com/fdyang/p/4919829.html