Search code examples
c++arraysvector

Vector array not showing correct ans but cout<<array[0] is right


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;
    }
};

Solution

  • 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.