搜狗的笔试题

13 篇文章 0 订阅

以前找工作的时候去笔试搜狗遇到下面的题目,当时就崩溃了,呵呵,后来我在CSDN上发帖了。不过还是不懂。今天在网上看到了一个和这个问题差不多的问题。我决定一定要搞定它。苦思冥想了2小时加高人同事的提示,写出下面算法。

题目:

一个长度为n的数组a[0],a[1],...,a[n-1]。现在更新数组的各个元素,即a[0]变为a[1]到a[n-1]的积,a[1]变为a[0]和a[2]到a[n-1]的积,...,a[n-1]为a[0]到a[n-2]的积。最后返回更新后数组的最大值。程序要求:要求1.具有线性复杂度。2.不能使用除法运算符。算法:实际array[i]更新后的值为前array[0]~array[i-1]的积和array[i+1]~array[n-1]的积相乘。从前向后扫描一遍数组把前i个元素的积存在数组a中。从后向前扫描一遍数组把后n-i-1个元素的积存在数组b中。

最后在扫描一遍数组更新值,其值为a中的前i个元素的积和b中的后n-i-1个元素的积相乘。

#include <stdio.h>
#include <assert.h>
#include <malloc.h>
#define NUM 10
#define NEGATIVE_INF -10000

long MaxMultiple(long *arrayPtr, int n)
{
	  assert(arrayPtr != NULL && n != 0);
	  int itor;
	  long max = NEGATIVE_INF;
	  
	  int *ptr1 = (int *)malloc(n * sizeof(int));
	  assert(ptr1 != NULL);
	  
	  int *ptr2 = (int *)malloc(n * sizeof(int));
	  assert(ptr2 != NULL);
	  
	  ptr1[0] = 1;
	  ptr2[n - 1] = 1;
	  
	  for(itor = 1; itor < n; itor++)
	  {
	 	    ptr1[itor] = ptr1[itor - 1] * arrayPtr[itor - 1];
	  }
	  
	  for(itor = n - 2; itor >= 0; itor--)
	  {
	  	  ptr2[itor] = ptr2[itor + 1] *arrayPtr[itor + 1];
	  }
	  
	  for(itor = 0; itor < n; itor++)
	  {
	  	  arrayPtr[itor] =ptr1[itor] * ptr2[itor];
	  }
	  
	  for(itor = 0; itor < n; itor++)
	  {
			if(arrayPtr[itor] > max)
	  		{
	  			  max = arrayPtr[itor];
	  		}
	  }
	  free(ptr1);
	  free(ptr2);
	  return max;
}
	 
int main()
{
	  long a[NUM] = {2,4,3,8,5,3,2,3,6,7};
	  int itor;
	  long max;
	  max = MaxMultiple(a,NUM);
	  printf("%d\n",max);
	  for(itor = 0; itor < NUM; itor++)
	  {
	      printf("%ld ",a[itor]);
	  }
	  printf("\n");
	  return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值