• 不引入新的数组,实现数组元素交换位置函数


             最近遇到一道C++的面试题,要求不引入新的数组,实现数组元素交换位置函数,看似挺简单的,却还是花费了我不少时间,这里记录下来,给大家一个简单的思路。题目的详细要求是:

            不引入新的数组,实现数组元素交换位置函数:void swap(int a[], int m, int n);比如,设m为3,n为4,a中的数据为:1 2 3 4 5 6 7,函数执行后,a中的数据为:4 5 6 7 1 2 3。

            这里的关键是不引入新的数组,而且尽量使用较少的额外变量。我的思路是采用“倒叙追踪法”,利用一个额外变量进行两个数的swap。贴一下代码,大家有什么更好的方法可以交流一下。

    #include <iostream>
    #include <unistd.h>

    using namespace std;

    int judge_pos(int i,int m,int n)
    {
        if(i>=0 && i<m)
        {
            return i+n;
        }
        else if(i>=m && i<(m+n))
        {
            return i-m;
        }
        else
        {
            return -1;
        }
    }
    int main()
    {
        int num_of_data;
        int i_array[1024];
        int m,n;

        cout << "How many numbers do you want to input: ";
        cin >> num_of_data;
        cout << "Input the numbers,separate with space: " << endl;
        for(int i=0;i<num_of_data;i++)
        {
            cin >> i_array[i];
        }
        cout << "Input m and n,separate with space; " << endl;
        cin >> m >> n;

        int i = 0;
        while(i_array[i]>=0)
        {
            for(int j=0;j<(m+n);j++)
            {
                if(judge_pos(j,m,n)==i)
                {

                    if(i_array[j]>0)
                    {
                        int temp = i_array[i];
                        i_array[i] = -i_array[j];
                        i_array[j] = temp;
                        i=j;
                        break;
                    }
                    else
                    {
                        i_array[i] *= (-1);
                        i=j;
                        break;
                    }

                }
            }
        }
        for(int i=0;i<num_of_data;i++)
        {
            if(i<(m+n))
            {
                i_array[i] *= (-1);
            }
            cout << i_array[i] << " ";
        }
        return 0;
    }

  • 相关阅读:
    2021寒假每日一题《棋盘挑战》
    2021寒假每日一题《货币系统》
    2021寒假每日一题《红与黑》
    2021寒假每日一题《字母图形》
    2021寒假每日一题《完全背包问题》
    2021寒假每日一题《找硬币》
    python 迭代器和生成器
    python for循环
    python集合
    python字符串常用操作
  • 原文地址:https://www.cnblogs.com/jiangxinnju/p/5516908.html
Copyright © 2020-2023  润新知