Home > Blockchain >  Return an array in Java within a function
Return an array in Java within a function

Time:01-18

I've written this code to problem from Leetcode in Java. Question 496 Next Greater Element I. Here I must return an array with its brackets, like output must be for example [-1,3,-1]. I cannot print it, but only return. How to do it?

Link for question from Leetcode https://leetcode.com/problems/next-greater-element-i/description/?envType=study-plan&id=programming-skills-i

public int[] nextGreaterElement(int[] nums1, int[] nums2) {
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0;i<nums1.length;i  ){
        for (int j = 0;j<nums2.length;j  ){
            if (nums1[i] == nums2[j]){
                try{
                    if(nums1[i] < nums2[j 1]){
                        list.add(nums2[j 1]);

                    }else{
                        list.add(-1);
                    }
                }catch (ArrayIndexOutOfBoundsException e){
                    list.add(-1);
                }
            }
        }
    }
    int[] array = list.stream().mapToInt(i->i).toArray();
    for (int i = 0; i<array.length;i  ){
        System.out.println(array[i]);
    }
    return new int[]{}array; // this is error (should return [-1,3,-1])
}

CodePudding user response:

The line return new int[]{}array; is not a statement. You are trying to return a new int[], which doesn't cause an error by itself, but adding the array after the new int[]{} does absolutely nothing and causes a compiler error. Just return the array you created above it.

    int[] array = list.stream().mapToInt(i->i).toArray();
    return array;

I tested your response:

  public static void main(String[] args) throws IOException
  {
    int[] nums1 = {4,1,2};
    int[] nums2 = {1,3,4,2};
    int[] expected = {-1,3,-1};

    var result = nextGreaterElement(nums1, nums2);

    if (Arrays.equals(expected, result)){
      System.out.println("They are the same");
    } else {
      System.out.println("They are different");
    }
  }

The output was They are the same.

  • Related