diff --git a/merge-sorted-array.java b/merge-sorted-array.java new file mode 100644 index 00000000..330c6c3c --- /dev/null +++ b/merge-sorted-array.java @@ -0,0 +1,27 @@ +// Time Complexity : O(m+n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : yes +// Three line explanation of solution in plain english : We use three pointers: one at the end of the valid elements in nums1 (m - 1), one at the end of nums2 (n - 1), and one at the end of nums1 (m + n - 1).We compare the elements pointed to by nums1 and nums2 and place the larger one at the end of nums1.After placing the element, we move the corresponding pointer backward and continue until all elements from nums2 are merged + +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + int len = m +n -1; + while(len != -1) { + if(n==0){ + break; + } + if(m==0 || nums1[m-1] < nums2[n-1]) { + nums1[len] = nums2[n-1]; + n--; + len--; + + } else{ + nums1[len] = nums1[m-1]; + len--; + m--; + + } + } + } +} + diff --git a/remove-duplicates-from-sorted-array-ii.java b/remove-duplicates-from-sorted-array-ii.java new file mode 100644 index 00000000..68ce18a9 --- /dev/null +++ b/remove-duplicates-from-sorted-array-ii.java @@ -0,0 +1,58 @@ +// Time Complexity : O(2n) = O(n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Three line explanation of solution in plain english : We use two pointers, slow and fast. The fast pointer moves forward and counts how many times the same digit appears. When the fast pointer encounters a new element or reaches the end of the array, we check the digit count. We take the minimum of the digit count and 2, and then use the slow pointer to update the array. Once the fast pointer reach the end of array we return the slow index. + +class Solution { + public int removeDuplicates(int[] nums) { + int slow =0; + int fast =0; + int count =0; + while(fast< nums.length) { + int curr = nums[fast]; + while(fast -1) { + if(matrix[row][col] == target) { + return true; + } else if(matrix[row][col] > target) { + col--; + } else { + row++; + } + } + return false; + } +}