Home > Software design >  am getting this error :" RangeError (index): Invalid value: Only valid value is 0: 1"
am getting this error :" RangeError (index): Invalid value: Only valid value is 0: 1"

Time:01-22

am trying to solve some leetcode problems and kept getting this error , but when i run the code in another compiler it runs okey , this is the code :

class Solution {
  double findMedianSortedArrays(List<int> nums1, List<int> nums2) {
    double median = 0;
    int m = nums1.length;
    int n = nums2.length;
    List<int> nums3 = [nums1, nums2].expand((x) => x).toList();
    if ((m   n) % 2 == 0) {`your text`
      int mid = (nums3.length / 2).toInt();
      median = (nums3[mid]   nums3[mid - 1]) / 2;
      return median;
    } else {
      int mid = (nums3.length / 2).ceil();
      median = nums3[mid].toDouble();
      return median;
    }
  }
}

this is the error:
Line 13: RangeError (index): Invalid value: Only valid value is 0: 1
#0      List.[] (dart:core-patch/growable_array.dart:264:36)
#1      Solution.findMedianSortedArrays (file:///solution.dart:13:21)
#2      main (file:///solution.dart:49:30)
<asynchronous suspension>
referring to this part  =>  # median = nums3[mid].toDouble();

it should return the median of two sorted tables , but i keep getting this error

CodePudding user response:

I can be wrong but in the use of [mid] you had a mid value of 1 when you did int mid = (nums3.length / 2).toInt(); it reached the result of 1, but the list was entirely empty (i.e. it was only []) causing the error.

You need to treat this exceptions however

I highly recommend checking other solutions like this one https://leetcode.com/problems/median-of-two-sorted-arrays/solutions/2651020/c-solution/ it wont cause the same issue. You must remember to consider errors and when empty results come

  • Related