我學習C++,最近遇上這個問題的順序。這個'-1'不應該是序列的一部分。打印出相反的順序,它也必須以-1結尾。因此,我寫了非常直截了當的代碼,它在性能方面可能不是最好的,就好像我計算的是正確的整體O(N^2/2)。倒車整數
int n = 0;
vector<int> numbers; //placeholder vector for input
while (n != -1) {
cin >> n;
numbers.push_back(n);
}
numbers.erase(numbers.end() - 1); // -1 should not be the part of the vector, so I erase it
n = numbers.size() - 1;
for (int i = 0; i < n/2; ++i) { //swapping
int tmp = numbers[i];
numbers[i] = numbers[n - i];
numbers[n - i] = tmp;
}
for (auto a : numbers) //printing out
cout << a << " "; //each integer in input and output is separated by spacebar
cout << -1; //last element should be '-1'
不幸的是,這段代碼通過了4/10個測試用例,這對我來說非常震撼。
如果有人能給我一些關於我的代碼或任何關於性能的一般性建議的錯誤提示,我將不勝感激。
順便說一句:O(N^2/2)= O(N^2) –
嘗試'爲(I = 0 ; i
你試過什麼樣的測試案例? –