Created
May 16, 2023 07:02
-
-
Save ritik-agrawal/afa96d2b18f72c6bc8f02327c94a4355 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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++; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Leet Code
Given two sorted integer arrays with respective lengths, we need to create one sorted array.
Achievements
Arrays.sort(ar)
is faster than the methodrearrange
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.