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;
    }
  • 相关阅读:
    【转】Java8学习笔记(1) -- 从函数式接口说起
    解决sublime text 2总是在新窗口中打开文件(标签中打开)
    Cocoapod安装使用
    使用工具来提升Android开发效率
    Material Design之FloatingActionButton的使用
    HDU2842-Chinese Rings(递推+矩阵高速幂)
    阿里笔试题(2015)持续更新中
    Newton‘ method 的优缺点
    解决的方法:warning: Clock skew detected. Your build may be incomplete.
    云享 值得一用的在线文档即时通讯平台 新用户持续免费
  • 原文地址:https://www.cnblogs.com/sdlypyzq/p/2161067.html
Copyright © 2011-2022 走看看