阅微客栈 » 头脑风暴

微软面试题:重排0,1数组

(8 posts)
  • 发起于 1 年 之前,作者 zhang
  • 最新回复 来自于 521zheng
  1. BM: you are given an array of integers containing only 0s and 1s. you have to place all the 0s in even position and 1s in odd position and if suppose no. of 0s exceed no. of 1s or vice versa then keep them untouched. Do that in ONE PASS and WITHOUT taking EXTRA MEMORY.

    input array:
    {0 1 1 0 1 0 1 0 1 1 1 0 0 1 0 1 1 }
    output array:
    {0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 }

    发布于 1 年 之前 #
  2. szuxjq
    Member

    题意不是很明白啊?“if suppose no if 0s exceed no. of 1s ”?

    发布于 1 年 之前 #
  3. 已经改了一下,不过还是不太懂

    发布于 1 年 之前 #
  4. sandacn
    Member

    swap from two end is Ok

    发布于 1 年 之前 #
  5. david
    Member

    if suppose no. of 0s exceed no. of 1s or vice versa then keep them untouched...
    如果0的个数比1的个数多,或相反,则使那些多出来的数字不显示出来。

    貌似是:

    input array:
    {0 1 1 0 1 0 1 0 1 1 1 0 0 1 0 1 1 }
    output array:
    {0 1 0 1 0 1 0 1 0 1 0 1 0 1 }

    发布于 1 年 之前 #
  6. i=-2,j=-1
    while(1)
    {
    do{i+=2;}while(A[i]==0);
    do{j+=2;}while(A[j]==1);
    if(i>n||j>n) break;
    swap(A[i],A[j]);
    }
    不知可行否?

    发布于 8 月 之前 #
  7. Wanting
    Member

    void sort01OnePass(int input[], int count) {
    if ((input == NULL) || (count == 0)) return;
    int i0 = 0;
    int i1 = 1;
    while (true) {
    while ((i0 < count) && (input[i0] == 0)) {
    i0 += 2;
    }
    if (i0 >= count) break;
    while ((i1 < count) && (input[i1] == 1)) {
    i1 += 2;
    }
    if (i1 >= count) break;
    input[i0] = 0;
    input[i1] = 1;
    }
    if (i0 >= count) { //We have all even positions set to 0, now we need to take care of the odd positions left.
    int iend = (count % 2 ==0)? (count - 1):(count - 2);
    while (true) {
    while ((i1 < iend) && (input[i1] == 1))
    i1 +=2;
    while ((iend > i1) && (input[iend] == 0))
    iend -= 2;
    if (i1 >= iend) break;
    input[i1] = 1;
    input[iend] = 0;
    }
    } else { //We have all odd numbers set to 1, now we need to take care of the even positions left.
    int iend = (count % 2 == 0)? (count - 2): (count - 1);
    while (true) {
    while ((i0 < iend) && (input[i0] == 0))
    i0 += 2;
    while ((iend > i0) && (input[iend] == 1)) {
    iend -= 2;
    }
    if (i0 >= iend) break;
    input[i0] = 0;
    input[iend] = 1;
    }
    }
    }

    发布于 8 月 之前 #
  8. 521zheng
    Member

    int arrangebinary(int * a, int n)
    {
    int pos =-1;
    for(int i=0;i<n;i++)
    {
    if(i%2 == a[i] && pos == i-1)
    {
    pos++;
    }
    else
    {
    if(i!=pos+1 && a[pos+1]!=a[i])
    {
    swap(a[pos+1], a[i]);
    pos+=2;
    }
    }
    }
    return 1;
    }

    发布于 7 月 之前 #

该主题的 RSS Feed

回复

你必须 登录 后发帖。