相信Android程序猿在找工作的过程中经常会遇到面试算法,下面是我记忆中的一些面试题,整理如下(尊重原创,转载请注明出处。原文地址):
private static void light()
{
int N = 100;
int[] light = new int[N];
for (int k = 1; k <= N; k++)
{
for (int i = 1; i <= N; i++)
{
int index = k * i - 1;
if (index < N)
{
light[index] = light[index] + 1;
}
else
{
break;
}
}
}
for (int i = 1; i <= N; i++)
{
if (light[i - 1] % 2 != 0)
{
System.out.print(i + "(" + light[i - 1] + ")\t");
}
}
}
程序输出:
1(1) 4(3) 9(3) 16(5) 25(3) 36(9) 49(3) 64(7) 81(5) 100(9)
分析
第一种思路:
第一个人切换的开关编号为i,i∈[1,n];
第二个人切换的开关编号为2i,i∈[1,n/2];
.
.
.
第k个人切换的开关编号为ki,i∈[1,n/k];
故,把所有切换的开关次数做和,由于一开始是关着的,所以只有奇数次切换,最后的状态才是开着的。
第二种思路:
1到100中,只有完全平方数(1,4,9,16,25,36,49,64,72,100)的约数是奇数个,故,最终只有这些编号的电灯是亮着的。
private static void strRevers()
{
char[] str = "abcdefghijkl".toCharArray();
int len = str.length;
for (int i = 0; i < len / 2; i++)
{
char c = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = c;
}
System.out.println(str);
}
private static void f3()
{
int b = 1;
for (int a = 0; a <= 9; a++)
{
for (int c = 0; c <= 9; c++)
{
if (a + c == 13)
{
System.out.println(a + "" + b + "" + c);
}
}
}
}
分析
由于a+c个位等于3,十位等于1,所以a+c = 13,所以b+b = 2。
private static void f4()
{
int[] arr = new int[] { 4, 6, 9, 52, 36, 97, -63, -55, -1, 64, -36 };
int len = arr.length;
int max = 0;
int min = 0;
for (int i = 0; i < len; i++)
{
if (arr[i] > max)
{
max = arr[i];
}
if (arr[i] < min)
{
min = arr[i];
}
}
System.out.println(Math.abs(max - min));
}
private static void f5()
{
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.printf("%2dx%2d=%2d ", j, i, i * j);
}
System.out.println("");
}
}
private static String strAnd(String str1, String str2)
{
String base = null;
String match = null;
if (str1.length() < str2.length())
{
match = str1;
base = str2;
}
else
{
match = str2;
base = str1;
}
int start = -1;
int end = -1;
String ret = null;
for (int i = 0; i < match.length(); i++)
{
char c = match.charAt(i);
if (base.indexOf(c) >= 0)
{
start = i;
break;
}
}
for (int i = match.length() - 1; i >= start; i--)
{
char c = match.charAt(i);
if (base.indexOf(c) >= 0)
{
end = i;
break;
}
}
ret = match.substring(start, end + 1);
if (base.indexOf(ret) >= 0)
{
return ret;
}
else
{
return strAnd(ret.substring(1), base);
}
}