diff --git a/Merge_sorted_array.java b/Merge_sorted_array.java new file mode 100644 index 00000000..6fd7bb78 --- /dev/null +++ b/Merge_sorted_array.java @@ -0,0 +1,29 @@ + +// 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- +//Use two pointers starting from the ends of both arrays and fill the first array from the back. +//Compare elements: place the larger one at the end and move that pointer backward. +//Repeat until all elements from both arrays are merged. +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + int p1=m-1, p2=n-1; + int idx=m+n-1; + while(p1>=0 && p2>=0){ + if(nums2[p2]>nums1[p1]){ + nums1[idx]= nums2[p2]; + p2--; + }else{ + nums1[idx]= nums1[p1]; + p1--; + } + idx--; + } + while(p2 >= 0){ + nums1[idx] = nums2[p2]; + p2--; + idx--; + } + } +} \ No newline at end of file diff --git a/Remove_dublicates.java b/Remove_dublicates.java new file mode 100644 index 00000000..b2314af1 --- /dev/null +++ b/Remove_dublicates.java @@ -0,0 +1,28 @@ +// Time Complexity : O(n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : yes +// Three line explanation of solution in plain english- +/* +1. Use two pointers, slow and fast, to traverse the array. +2. Keep track of the count of consecutive duplicate elements. +3. Only keep elements that appear at most twice. + */ +class Solution { + public int removeDuplicates(int[] nums) { + // if(nums.length==null) return -1; + int slow = 1; + // int fast = 1; + int c = 1; + + for(int fast=1; fast= 0) { + if (matrix[row][col] == target) { + return true; + } else if (matrix[row][col] > target) { + col--; // Target is smaller, move left + } else { + row++; // Target is bigger, move down + } + } + return false; + } +} \ No newline at end of file