diff --git a/DuplicatesFromSortedArray2.java b/DuplicatesFromSortedArray2.java new file mode 100644 index 00000000..350f3791 --- /dev/null +++ b/DuplicatesFromSortedArray2.java @@ -0,0 +1,24 @@ +// Time Complexity : O(n). +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Approach : We have two pointers, one used to swap and other to iterate through the array. We increase the counter if two elements are +// equal adn based on the condition we swap in the array so that the final resultant array is achieved. + +class Solution { + public int removeDuplicates(int[] nums) { + int count = 1; + int j = 1;//pinter for swapping result elements + for(int i=1;i=0 && p2>=0){ //until both arrays wont reach out of bounds + if(nums1[p1] <= nums2[p2]){ + nums1[idx] = nums2[p2];//add the greater one from nums2 to nums1 + p2--; + idx--; + } else{ + nums1[idx] = nums1[p1];//shift the greater one to end pointer in nums1 + p1--; + idx--; + } + } + while(p2>=0){//if still elements are left in nums2, move to nums1 + nums1[idx] = nums2[p2]; + p2--; + idx--; + } + } +} \ No newline at end of file diff --git a/SearchIn2DArray.java b/SearchIn2DArray.java new file mode 100644 index 00000000..98d7e33b --- /dev/null +++ b/SearchIn2DArray.java @@ -0,0 +1,25 @@ +// Time Complexity : O(m+n). +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Approach : We start looping from [0][n-1] or [m-1][0] as from these points we see a pattern of increasing on one direction and decreasing +// on another direction. So I picked [0][n-1], compared it with target and moved the pointer lo left if target is greater or moved the +// pointer down if target is lower. + +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int m = matrix.length; + int n = matrix[0].length; + int i = 0; + int j = n-1; + while(i=0){ // boundary conditions + if(matrix[i][j] == target){ + return true; + } else if(target > matrix[i][j]){ + i++; // move towards bottom in 2d matrix visualization + } else{ + j--;// move towards left in 2d matrix visualization + } + } + return false; + } +} \ No newline at end of file