昨天晚上在群裡聊天時,有位朋友問一道百度的筆試題如何解答,當時好像並沒有人能夠按照要求解答出來,我今天用工作之餘的時間想了出來,但不知對否,用vc6可以跑,並且執行正確。大家來多提提意見。
題目是這樣的:
百度面試題,假設一整型數組存在若干正數和負數,現在通過某種演算法使得該數組的所有負數在正數的左邊,
且保證負數件和正數間元素相對位置不變。時空複雜度要求分別為:o(n),o(1)
例如
-3 4 2 -1 7 3 -5
排序後
-3 -1 -5 4 2 7 3
在解答題目之前,我首先測試了一下memset()的使用方法,
函數名: memset
功 能: 設定s中的所有位元組為ch, s數組的大小由n給定
用 法: void *memset(void *s, char ch, unsigned n);
程式例:
#include <string.h>
#include <stdio.h>
#include <mem.h>
int main(void)
{
char buffer[] = "Hello world\n";
printf("Buffer before memset: %s\n", buffer);
memset(buffer, '*', strlen(buffer) - 1);
printf("Buffer after memset: %s\n", buffer);
return 0;
}
如果是要拷貝的源字元與目標字串有重疊地區怎麼辦?拷貝會出錯嗎?我測試了一下,是沒問題的。
char str[30] = "0123456789";
memcpy(&str[0],&str[5],10);
printf("%s\n",str);
// memcpy(&str[5],&str[0],10);----->012340123456789
// memcpy(&str[0],&str[5],10);----->56789
下面貼出解答那道 題的代碼,希望大家多多指教
// TestBaidu.cpp : Defines the entry point for the console application.
//
/*
百度面試題,假設一整型數組存在若干正數和負數,現在通過某種演算法使得該數組的所有負數在正數的左邊,
且保證負數件和正數間元素相對位置不變。時空複雜度要求分別為:o(n),o(1)
例如
-3 4 2 -1 7 3 -5
排序後
-3 -1 -5 4 2 7 3
*/
#include "stdafx.h"
//#include <stdio.h>
#include <string.h>
void print_arr(int *p, int n)
{
for(int i=0; i<n; i++)
{
printf("%3d ",p[i]);
}
printf("\n");
}
int main(int argc, char* argv[])
{
/*
char str[30] = "0123456789";
memcpy(&str[0],&str[5],10);
printf("%s\n",str);
// memcpy(&str[5],&str[0],10);----->012340123456789
// memcpy(&str[0],&str[5],10);----->56789
*/
int a[] = {-3,4,2,-1,7,3,-5};
int len = sizeof(a)/sizeof(int);
printf("%3d : ",0);
print_arr(a,len);
int count=0;
int temp;
for(int i=0; i<len; i++)
{
if(a[i] < 0)
{
if(count>0)
{
temp = a[i];
memcpy(&a[i-count+1],&a[i-count],count*sizeof(int));
a[i-count] = temp;
}
}
else if(a[i] > 0)
{
count++;
}
printf("%3d : ",i);
print_arr(a,len);
}
printf("%3d : ",0);
print_arr(a,len);
printf("Hello World!\n");
return 0;
}