滴滴面試題第一道

/**
算法思想:遍歷輸入流,將符號和數字分開存到兩個數組裏,減號作爲數字的負數。
然後在符號集裏面找*或者/,找到就把對應的數組集兩個操作數比較並排序。
然後數組被分割成三段,中間是乘法和兩個交換數,兩邊是沒有操作的數據,然後分別對兩邊做遞歸。
如果沒有找到*或者/說明全是加法,直接對數組的數據進行排序。
*/
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;

/**
6
1 + 2 + 1 + -4 * -5 + 1
1 + 1 + 2 + -5 * -4 + 1
 */

int data[100];
char fuhao[100];

/**
 * 快排序
 * @param a
 * @param low
 * @param high
 */
void quickSort(int a[], int low ,int high)
{
    if(low<high)
    {
        int i = low, j = high;
        int x = a[low];
        while(i<j)
        {
            while(i<j && a[j] >= x) j--;
            if(i<j) a[i++] = a[j];
            while(i<j && a[i] <= x) i++;
            if(i<j) a[j--] = a[i];
        }
        a[i] = x;
        quickSort(a, low ,i-1);
        quickSort(a, i+1 ,high);
    }
}

void mySort(int data[], char fuhao[], int begin, int end){
    for (int i = begin; i < end; ++i) {
        if (fuhao[i] == '*' || fuhao[i] == '/'){
            // 先對乘除兩邊進行排序
            if (data[i] > data[i+1]){
                int temp = data[i];
                data[i] = data[i+1];
                data[i+1] = temp;
            }

            mySort(data, fuhao, begin, i-1);
            mySort(data, fuhao, i+2, end);
            return;
        }
    }

    // 沒有乘除號,就對+-的數字進行排序
    quickSort(data, begin, end);
}

int main() {

    int n = -1;
    char temp;
    int size_data = 0;
    int size_fuhao = 0;
    scanf("%d", &n);
    getchar();
    scanf("%c", &temp);

    int num = 0;
    bool munes = false;
    while (temp != '\n'){
        if (temp == '+' || temp == '*' || temp == '/'){
            // 添加數字
            if (munes){
                num = -num;
            }
            data[size_data++] = num;
            num = 0;
            munes = false;

            // 添加符號
            fuhao[size_fuhao++] = temp;
        }
        else if (temp >= '0' && temp <= '9'){
            num = num*10 + temp - '0';
        } else if (temp == '-'){
            // 遇見負號
            munes = true;
        }

        scanf("%c", &temp);
    }
    data[size_data++] = num;
    mySort(data, fuhao, 0, size_data-1);

    for (int i = 0; i < size_data - 1; ++i) {
        printf("%d", data[i]);
        printf("%c", fuhao[i]);
    }

    cout<< data[size_data-1];
    return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章