Skip to content

Instantly share code, notes, and snippets.

@ritik-agrawal
Created May 16, 2023 07:02
Show Gist options
  • Save ritik-agrawal/afa96d2b18f72c6bc8f02327c94a4355 to your computer and use it in GitHub Desktop.
Save ritik-agrawal/afa96d2b18f72c6bc8f02327c94a4355 to your computer and use it in GitHub Desktop.
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
if (n == 0){
return;
}
var cur = 0;
var ptr = 0;
while (cur < n && ptr < m){
if (nums1[ptr] == nums2[cur]){
ptr++;
continue;
}
if (nums1[ptr] > nums2[cur]){
swap(nums1, nums2, ptr, cur);
Arrays.sort(nums2);
}
ptr++;
}
while(cur < n){
swap(nums1, nums2, ptr++, cur++);
}
}
private void swap(int[] arr, int[] arr1, int a, int b){
var tmp = arr[a];
arr[a] = arr1[b];
arr1[b] = tmp;
}
private void rearrange(int[] arr, int cur){
System.out.println("Im here");
var alen = arr.length;
if(cur == alen){
return;
}
if ((cur+1) < alen && arr[cur] < arr[cur + 1]){
return;
}
var ptr = cur+1;
while(ptr < alen && arr[ptr] <= arr[cur]){
swap(arr, arr, ptr, cur);
cur = ptr;
ptr++;
}
}
}
@ritik-agrawal
Copy link
Author

Leet Code

Given two sorted integer arrays with respective lengths, we need to create one sorted array.

Achievements

  • The above-mentioned code is done by myself.
  • The runtime of the solution is 1ms which beats 30% of the total solutions submitted and 66% of the total solutions in terms of space.
  • It has been observed that the Java library method Arrays.sort(ar) is faster than the method rearrange created in the above code. Using the Java library reduced the runtime to 1ms from 7ms.

Better solution

The below mentioned code is learned from Leet code solutions section and the runtime is 0ms.

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        var k = (m+n-1);
        var i = m-1;
        var j = n-1;

        while(i>=0 && j>=0){
            if(nums1[i] > nums2[j]){
                nums1[k] = nums1[i];
                i--; 
            } else {
                nums1[k] = nums2[j];
                j--;
            }
            k--;
        }
        while(j>=0){
            nums1[k] = nums2[j];
            k--;
            j--;
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment