zoukankan      html  css  js  c++  java
  • 一首笔试题 C实现

      昨天晚上在群里聊天时,有位朋友问一道百度的笔试题如何解答,当时好像并没有人能够按照要求解答出来,我今天用工作之余的时间想了出来,但不知对否,用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);
    return0;
    }

    如果是要拷贝的源字符与目标字符串有重叠区域怎么办?拷贝会出错吗?我测试了一下,是没问题的。

    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;
    }
    }
    elseif(a[i] >0)
    {
    count
    ++;
    }

    printf(
    "%3d : ",i);
    print_arr(a,len);
    }
    printf(
    "%3d : ",0);
    print_arr(a,len);

    printf(
    "Hello World!\n");
    return0;
    }
  • 相关阅读:
    hdu6229 Wandering Robots 2017沈阳区域赛M题 思维加map
    hdu6223 Infinite Fraction Path 2017沈阳区域赛G题 bfs加剪枝(好题)
    hdu6438 Buy and Resell 买卖物品 ccpc网络赛 贪心
    hdu6441 Find Integer 求勾股数 费马大定理
    bzoj 1176 Mokia
    luogu 3415 祭坛
    bzoj 1010 玩具装箱
    bzoj 3312 No Change
    luogu 3383【模板】线性筛素数
    bzoj 1067 降雨量
  • 原文地址:https://www.cnblogs.com/sdlypyzq/p/2161067.html
Copyright © 2011-2022 走看看