commit 4eb0764e779ed1e4c18cdc3b00c8142e9a41bc98 parent d05438814490db10058c550afb58d0872f817e23 Author: AndrewLockVI <andrewlaack1@gmail.com> Date: Wed, 19 Apr 2023 19:20:38 -0500 Merge two sorted lists Diffstat:
| A | merge-sorted-array/merge-sorted-arrays.dart | | | 38 | ++++++++++++++++++++++++++++++++++++++ |
1 file changed, 38 insertions(+), 0 deletions(-)
diff --git a/merge-sorted-array/merge-sorted-arrays.dart b/merge-sorted-array/merge-sorted-arrays.dart @@ -0,0 +1,38 @@ + +//This is an algorithm to merge two arrays together that are pre-sorted. Given this +//my algorithm is the optimal one and has a time complexity of O(n) which makes it +//a linear time complexity algorithm. + +//Runtime: 238ms Beats: 98.70% +//Memory: 140.2MB Beats: 100% + +class Solution { + void merge(List<int> nums1, int m, List<int> nums2, int n) { + + List<int> nums = nums1.sublist(0,m); + int l1 = 0; + int l2 = 0; + int index = 0; + while(l1 < m && l2 < n){ + if(nums[l1] < nums2[l2]){ + nums1[index] = nums[l1]; + l1 += 1; + } + else{ + nums1[index] = nums2[l2]; + l2 += 1; + } + index += 1; + } + while(l1 < m){ + nums1[index] = nums[l1]; + index += 1; + l1 += 1; + } + while(l2 < n){ + nums1[index] = nums2[l2]; + index += 1; + l2 += 1; + } + } +}