使用C++和双指针算法移除数组中的元素,且原地移除,不使用额外的空间

输入一个数组nums和一个值val,在该数组中,凡是与val相等的元素全部移除,并最终输出该数组,C++代码如下:

#include
#include
#include//计算代码所需要的时间
using namespace std;

class Solution
{
public:
    int removeElement(vector& nums, int val)
    {
        int numsize = nums.size();
        int fast = 0, slow = 0;
        for (fast = 0; fast < numsize; fast++)
        {
            if (nums[fast] != val)
            {
                nums[slow] = nums[fast];
                slow++;
            }
        }
        return slow;
    }
};

int main()
{
	clock_t starttime, endtime;
	starttime = clock();//计时开始
    Solution solution;
    vector v;
    int x,val;
    cout << "请输入数组:" << endl;
    while (cin>>x)
    {
        v.push_back(x);
        if (cin.get()=='\n')
        {
            break;
        }
    }
    cout << "原数组为:" << endl;
    for (int i = 0; i < v.size(); i++)
    {
        cout << v[i] << " ";
    }
    cout << endl;
    cout << "请输入需要移除的值:" << endl;;
    cin >> val;
    int slow = solution.removeElement(v,val);
    cout << "slow的值为:" << slow << endl;
    v.resize(slow);
    cout << "最终数组为:" << endl;
    for (int i = 0; i < v.size(); i++)
    {
        cout << v[i] << " ";
    }
    cout << endl;
	endtime = clock();//计时结束
	cout << "运行时间为: " << (double)(endtime - starttime) / CLOCKS_PER_SEC << "s" << endl;
	system("pause");
	return 0;
}

注意事项:

       在使用while(cin>>x)循环输入时,一定要把跳出循环的代码写在数组赋值代码的后面,否则就无法将所有数据全部放进数组中,就会导致失败

你可能感兴趣的:(c++,数据结构与算法,经验分享,算法,c++,数据结构,双指针,数组,vector)