一首筆試題 C實現

來源:互聯網
上載者:User

  昨天晚上在群裡聊天時,有位朋友問一道百度的筆試題如何解答,當時好像並沒有人能夠按照要求解答出來,我今天用工作之餘的時間想了出來,但不知對否,用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;
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.