0

I searched there a few times but came across nothing specifically with this. I have completed this question and here is my code;

int[][] input = {{0}, {0,1}, {4,3,2,1}, {32, 56, 67, 98, 97,8888, 35}};

    for(int row = 0; row<input.length; row++) {
    Arrays.sort(input[row]);
    for(int col = 0; col<input[row].length; col++) {
        if (input[row].length < 2) {
            System.out.print(0 + " ");
        } else {
            System.out.print(input[row][1] + " ");
            break;
        }
    }
    }

Why I felt the need to post this is to simply inquire, is there a better and more efficient way to answer this question? I simply sorted my arrays and printed the first element which would be the second smallest number. But I am thinking about a better way to complete this question if there were millions of records?

2
  • 1) Don't sort the inner array if length < 2. --- 2) What's the point of the inner loop? You never use col for anything. Also means you don't print anything if length == 0. --- 3) See duplicate. Commented Apr 9, 2018 at 18:53
  • Yes. There is no need for nested loops here. Iterate through your array once: first check length (if length < 2) then continue to next iteration. If length >= 2, sort and print out input[row][1]. Time complexity of that would be O(n) versus your code is O(n^2). Commented Apr 9, 2018 at 18:58

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.