百度的笔试题

来源:互联网 发布:淘宝快递费用价格表 编辑:程序博客网 时间:2024/06/05 08:10
2.一个文件,内含一千万行字符串,每个字符串在1K 以内,要求找出所有相反的串对,如abc 和cba。
ANSWER

So we have ~10G data. It is unlikely to put them all into main memory. Anyway, calculate the hash of each line in the first round, at the second round calculate the hash of the reverse of the line and remembers only the line number pairs that the hashes of the two directions collides. The last round only test those lines.


第一种方法:trie树,遍历文件,对每个字符串先逆置,判断逆置的字符串是否在trie树中,如果在,则当前字符串和逆置的字符串可连接。

第二种方法:hadoop。 每个每个字符串形成两个(key,vlaue)




程序员面试题精选100题(61)-数对之差的最大值[算法]  

从左到右保存当前元素之前的最大值,减去当前元素,即记得以此元素为尾的最大差值。时间复杂度O(n) 空间复杂度O(1)
int findmaxdif(int *pdata,int n)
{
   if(pdata==NULL || n<=0)
       throw new exception(“error input”);
   if(n==1)
       return 0;
  int maxdif=0X80000000;
  int maxnum=pdata[0];
  for(int i=1;i<n;++i)
  {
       if(pdata[i-1]>max)
              max=pdata[i];
       int difcurr=max-pdata[i];
       if(difcurr>maxdif)
          maxdif=dircurr;
  }
  return maxdif;
}

或者更简单的从后先前
nt solve(int array[], int n)
{
int min_v = array[n-1], ans = 0;
for (int i = n - 2; i >= 0; --i)
{
            ans = max(ans, array[i] - min_v);
            min_v = min(min_v, array[i]);
}
return ans;
}


原创粉丝点击