diff --git a/Merge-sorted-array.java b/Merge-sorted-array.java new file mode 100644 index 00000000..b31b068c --- /dev/null +++ b/Merge-sorted-array.java @@ -0,0 +1,24 @@ +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + int p1 = m-1; + int p2 = n-1; + int p3 = m+n-1; + while(p1>=0 && p2>=0){ + if(nums1[p1] <= nums2[p2]){ + nums1[p3] = nums2[p2]; + p2--; + p3--; + }else { + nums1[p3] = nums1[p1]; + p1--; + p3--; + } + } + + while(p2>=0){ + nums1[p3] = nums2[p2]; + p2--; + p3--; + } + } +} \ No newline at end of file diff --git a/README.md b/README.md index e1a6f9d6..a6088885 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,16 @@ # Two-Pointers-2 ## Problem1 (https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/) +* Brutforce - Hasshmap freq map, keep 2 elements +* Optimal - no extra space used. keep 2 ptrs- i for iterating array, slow ptr for keeping the freq count <=2. ## Problem2 (https://leetcode.com/problems/merge-sorted-array/) +* Brutforce - Copy nums2 arr behind nums1 arr & then sort it - T(n) = O(m+n log(m+n)) +* Optimal - 3 pointers p1 for nums1 at m-1, p2 for nums2 at n-1, p3 for num1 at m+n-1. +* comparing p1 & p2 whichever is greater keeping at p3. Look for condition where p2 will still be inbound that time copy elements from p2 to nums1 array at p3. ## Problem3 (https://leetcode.com/problems/search-a-2d-matrix-ii/) - +* Top Right or Bottom Left elements have deciding factor - whether to go up/down or left/right. +* Search the target within limits. diff --git a/Remove-duplicates-from-sorted-array-ii.java b/Remove-duplicates-from-sorted-array-ii.java new file mode 100644 index 00000000..56c0cccc --- /dev/null +++ b/Remove-duplicates-from-sorted-array-ii.java @@ -0,0 +1,18 @@ +class Solution { + public int removeDuplicates(int[] nums) { + int count = 1; + int slow = 1; + for(int i=1;i=0){ + if(matrix[r][c] == target) { + return true; + }else if(matrix[r][c] < target){ + r++; + }else{ + c--; + } + } + + return false; + } +} \ No newline at end of file