日期:2014-05-20  浏览次数:20944 次

面试程序题
本帖最后由 qiyuexuel 于 2013-08-19 23:06:08 编辑
一、写一个函数 传入一个数组和N 要求把前N个元素移到最后 需要占用最少内存
     比如传入[a b c d e], N=2, 要求返回数组[c d e a b]

二、in case you are not familiar with regular expression substitution, here's a quick tutorial:

the syntax of string substitution is:
VARIABLE =~ s/SEARCH_PATTERN/NEW_STRING/

For example,
$a = 'abc,123';
$a =~ s/(\w+),(\w+)/\2,\1/; # $a is now '123,abc' because \1='abc' and \2='123'

Here's the question:
write ONE substitution statement(ie. s/SEARCH_PATTERN/NEW_STRING/) so that
"<date>1999-02-25</date>" will be updated to "<date>02-25-1999</date>" AND
"<date>2005-11-03</date>" will be updated to "<date>11-03-2005</date>"
面试 内存 数组

------解决方案--------------------
一.
题目相当于循环左移n位。移位问题可以转换为两次反转交换问题。
如:
 比如传入[a b c d e], N=2, 要求返回数组[c d e a b]

第一步:
把ab反转交换为ba
把cde反转交换为edc
字符串变为baedc
第二部:
把整个字符反转交换
变为:cdeab。
空间复杂度为O(1)
时间复杂度为O(n)
代码如下:


void swap(int A[],int n,int k)
{
  for(int i=0,j=k-1;i<j;i++,j--)
  {
      int temp=A[i];
      A[i]=A[j];
      A[j]=A[i];
   }
   for(int i=k,j=n-1;i<j;i++,j--)
  {
      int temp=A[i];
      A[i]=A[j];
      A[j]=A[i];
   }
    for(int i=0,j=n-1;i<j;i++,j--)
  {
      int temp=A[i];
      A[i]=A[j];
      A[j]=A[i];
   }