Guest User

Untitled

a guest
Feb 25th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. class Solution {
  2. public void merge(int[] nums1, int m, int[] nums2, int n) {
  3. // Checking edge case: if nums2 is empty, we can just return whatever nums1 is, since it's already sorted.
  4. if (n == 0) {
  5. return;
  6. }
  7. // Checking edge case: if nums1 is empty, we just copy all nums2 values into nums1
  8. if (m == 0) {
  9. for(int i = 0; i < n; i++) {
  10. nums1[i] = nums2[i];
  11. }
  12. return;
  13. }
  14.  
  15. // Approach: we're going backwards since we know the end is empty, and the two arrays are already sorted.
  16. int nums1Index = m-1;
  17. int nums2Index = n-1;
  18. int sortedArrayIndex = m + n -1;
  19.  
  20. while (nums1Index >= 0 && nums2Index >= 0) {
  21. if(nums1[nums1Index] < nums2[nums2Index]) {
  22. nums1[sortedArrayIndex--] = nums2[nums2Index--];
  23. } else {
  24. nums1[sortedArrayIndex--] = nums1[nums1Index--];
  25. }
  26. }
  27.  
  28. // Going through leftover values.
  29. while (nums1Index >= 0) {
  30. nums1[sortedArrayIndex--] = nums1[nums1Index--];
  31. }
  32. while (nums2Index >= 0) {
  33. nums1[sortedArrayIndex--] = nums2[nums2Index--];
  34. }
  35. }
  36. }
Add Comment
Please, Sign In to add comment