What's wrong with my solution? Showing expected result locally! But oj saying wrong answer


  • 0
    S

    Don't know what's wrong with my solution? This solution showing expected result locally, but in oj it's showing wrong answer for
    input: [[1,2],[3,4]]
    Output: [[1,2],[3,4]]
    Expected: [[3,1],[4,2]]

    Locally I am getting [[3,1],[4,2]]

    Here is my code:

    public class Solution {
        public void rotate(int[][] matrix) {
            int l = matrix.length;
            int[][] res = new int[l][l];
            
            for(int i = 0; i < l; i++){
                for(int j = 0; j < l; j++){
                    res[j][l-1-i] = matrix[i][j];
                }
            }
            matrix = res;
        }
    }

  • 2
    I

    The last step doesnt work here. I think leetcode doesnt allow you do matrix = res in JAVA. Please try:

    public class Solution {
        public void rotate(int[][] matrix) {
            int l = matrix.length;
            int[][] res = new int[l][l];
            for(int i = 0; i < l; i++){
                for(int j = 0; j < l; j++){
                    res[j][l-1-i] = matrix[i][j];
                }
            }
            for(int i = 0; i < l; i++){
                for(int j = 0; j < l; j++){
                    matrix[i][j] = res[i][j];
                }
            }
        }
    }

  • 0
    K
    This post is deleted!

  • 0
    S

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example

    Pay attention to "Writing code? Select all code then click on the {} button to preserve code formatting.” above text editor.


  • 0
    W

    The last line matrix = res won't work. matrix is a local variable. Modifying a local variable doesn't change its value outside the method.

    public static void main(String[] args)
    {
        int a = 1;
        change(a);
        System.out.println(a);    // print 1, not 2;
    }
    
    public static void change(int a)
    {
        a = 2;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.