英文:
Vector array not showing correct ans but cout<<array[0] is right
问题
以下是您提供的内容的翻译:
Image Leetcode 189
为什么答案错误?
当返回向量数组 temp 时,显示错误答案,但是当我使用遍历时,答案完全正确。我哪里错了?
请帮忙 xx
我正在对数组 nums 进行正确的旋转。创建了一个向量数组 temp,并应用了自己的逻辑并编写了代码,答案不匹配,
FYI,测试用例中的 nums 是 1,2,3,4,5,6,7,k=3
PFA,代码和输出
using namespace std;
class Solution {
public:
vector<int> rotate(vector<int>& nums, int k) {
int n=nums.size();
vector<int>temp(n);
//将最后的 k 个元素复制到 temp 中
for(int i=n-k; i<n; i++){
temp[i-(n-k)] = nums[i];
}
//剩余部分
for(int i=0; i<(n-k); i++){
temp[i+k] = nums[i];
}
cout<<temp[0];
return temp;
}
};
英文:
Image Leetcode 189
Why is the answer coming wrong?
The vector array temp when returned shows wrong answer but when i cout using traversal it is completely right. where am i going wrong?
please help xx
i was doing right rotation of the array nums. created a vector array temp, and applied my own logic and wrote the code,the answer is not matching,
FYI the nums in the TC is 1,2,3,4,5,6,7 and k=3
PFA, the code and the output
using namespace std;
class Solution {
public:
vector<int> rotate(vector<int>& nums, int k) {
int n=nums.size();
vector<int>temp(n);
//copying last k elements in temp
for(int i=n-k; i<n; i++){
temp[i-(n-k)] = nums[i];
}
//remain
for(int i=0; i<(n-k); i++){
temp[i+k] = nums[i];
}
cout<<temp[0];
return temp;
}
};
答案1
得分: 4
如果我没有错的话,你改变了 rotate
方法的参数。
原始问题中有一个 void rotate(vector<int>& nums, int k)
。所以你在那里返回的 temp
可能只是被问题忽略了。
你应该修改 nums
而不是返回值。
英文:
If I am not wrong you changed the firm of the rotate
method.
The original question had a void rotate(vector<int>& nums, int k)
. So temp
that you are returning there, is probably just ignored by the problem.
You should modify nums
instead.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论