leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

merge-sorted-arrays.dart (847B)


      1 
      2 //This is an algorithm to merge two arrays together that are pre-sorted. Given this
      3 //my algorithm is the optimal one and has a time complexity of O(n) which makes it
      4 //a linear time complexity algorithm.
      5 
      6 //Runtime: 238ms Beats: 98.70%
      7 //Memory: 140.2MB Beats: 100%
      8 
      9 class Solution {
     10   void merge(List<int> nums1, int m, List<int> nums2, int n) {
     11     
     12     List<int> nums = nums1.sublist(0,m);
     13     int l1 = 0;
     14     int l2 = 0;
     15     int index = 0;
     16     while(l1 < m && l2 < n){
     17       if(nums[l1] < nums2[l2]){
     18         nums1[index] = nums[l1];
     19         l1 += 1;
     20       }
     21       else{
     22         nums1[index] = nums2[l2];
     23         l2 += 1;
     24       }
     25       index += 1;
     26     }
     27     while(l1 < m){
     28       nums1[index] = nums[l1];
     29       index += 1;
     30       l1 += 1;
     31     }
     32       while(l2 < n){
     33       nums1[index] = nums2[l2];
     34       index += 1;
     35       l2 += 1;
     36     }
     37   }
     38 }