Vector数组未显示正确的结果,但`cout<

huangapple go评论71阅读模式
英文:

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&lt;int&gt; rotate(vector&lt;int&gt;&amp; nums, int k) {
        int n=nums.size();
        vector&lt;int&gt;temp(n);

        //将最后的 k 个元素复制到 temp 中
        for(int i=n-k; i&lt;n; i++){
            temp[i-(n-k)] = nums[i];
        }
        //剩余部分
        for(int i=0; i&lt;(n-k); i++){
            temp[i+k] = nums[i];
        }
        cout&lt;&lt;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&lt;int&gt; rotate(vector&lt;int&gt;&amp; nums, int k) {
        int n=nums.size();
        vector&lt;int&gt;temp(n);

        //copying last k elements in temp
        for(int i=n-k; i&lt;n; i++){
            temp[i-(n-k)] = nums[i];
        }
        //remain
        for(int i=0; i&lt;(n-k); i++){
            temp[i+k] = nums[i];
        }
        cout&lt;&lt;temp[0];
        return temp;
    }
};

答案1

得分: 4

如果我没有错的话,你改变了 rotate 方法的参数。
原始问题中有一个 void rotate(vector&lt;int&gt;&amp; 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&lt;int&gt;&amp; nums, int k). So temp that you are returning there, is probably just ignored by the problem.

You should modify nums instead.

huangapple
  • 本文由 发表于 2023年7月11日 13:16:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76658880.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定