1. Given a rectangular (cuboidal for the puritans) cake with a rectangular piece removed (any size or orientation), how would you cut the remainder of the cake into two equal halves with one straight cut of a knife ?
译:给定一块已在任意位置用任意方向切去一个矩形块的矩形蛋糕(注意是立体的,质量均匀的),怎样用一刀切出相等重量的两块来?
这道题目解答有很好的作答,可以参考
2. You're given an array containing both positive and negative integers and required to find the sub-array with the largest sum (O(N) a la KBL). Write a routine in C for the above.
原来想法非常复杂,后来看到网上别人的解答感到十分的好
int main()
{
{
int a[] ={ -2,30,-5,-13,-19,1,-3,2};
int len=8;
int sum=0,beg=0,end=0,maxBeg=0,maxEnd=0,maxSum=0,i=0;
maxBeg=i;
maxEnd=i;
int len=8;
int sum=0,beg=0,end=0,maxBeg=0,maxEnd=0,maxSum=0,i=0;
maxBeg=i;
maxEnd=i;
while (i < len)
{
sum +=a [ i ];
if( sum > maxSum )
{
maxSum = sum;
maxEnd = end;
maxBeg = beg;
}
else if( sum < 0 )
{
beg = i + 1;
sum = 0;
}
i++;
end++;
}
printf("beg %d,end %d,sum %d",maxBeg,maxEnd,maxSum);
{
sum +=a [ i ];
if( sum > maxSum )
{
maxSum = sum;
maxEnd = end;
maxBeg = beg;
}
else if( sum < 0 )
{
beg = i + 1;
sum = 0;
}
i++;
end++;
}
printf("beg %d,end %d,sum %d",maxBeg,maxEnd,maxSum);
return 0;
}
}
3. Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like. [ I ended up giving about 4 or 5 different solutions for this, each supposedly better than the others ].
这道题确实有很多方法解决,在这里我使用了hash表的方式,因为字符不多,也不至于浪费太多空间,而时间代价却是O(n)的
int main()
{
{
char str[] = " ";//input the sentence to check
char remove[ 256 ];//record the word in the sentence
for ( int i = 0; i < 256; i++ )
remove[ i ] = 0;
for( i = 0; i < strlen( str ); i ++ )
{
if ( remove[ str[ i ] ] ) break;
remove[ str[ i ] ] = 1;
}
if ( i == strlen( str ) ) cout << "there are no same words/n";
else cout << str[ i ] << " has at least two!/n";
char remove[ 256 ];//record the word in the sentence
for ( int i = 0; i < 256; i++ )
remove[ i ] = 0;
for( i = 0; i < strlen( str ); i ++ )
{
if ( remove[ str[ i ] ] ) break;
remove[ str[ i ] ] = 1;
}
if ( i == strlen( str ) ) cout << "there are no same words/n";
else cout << str[ i ] << " has at least two!/n";
return 0;
}
}