diff --git a/MergeSortedArray.java b/MergeSortedArray.java new file mode 100644 index 00000000..916c8668 --- /dev/null +++ b/MergeSortedArray.java @@ -0,0 +1,29 @@ +// https://leetcode.com/problems/merge-sorted-array/description +// Time complexity : O(m+n) where m is number of elements in num1 and n is number of elements in num2 +// Space complexity : O(1) +// Did this code successfully run on Leetcode : yes +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + int i = m-1; + int j = n-1; + int k = m+n-1; + while(i>=0 && j>=0){ + int val1 = nums1[i]; + int val2 = nums2[j]; + if(val1>val2){ + nums1[k] = val1; + i--; + k--; + }else{ + nums1[k] = val2; + j--; + k--; + } + } + while(j>=0){ + nums1[k] = nums2[j]; + j--; + k--; + } + } +} \ No newline at end of file diff --git a/Sample.java b/Sample.java index 960e272d..2823fce9 100644 --- a/Sample.java +++ b/Sample.java @@ -5,3 +5,30 @@ // Three line explanation of solution in plain english // Your code here along with comments explaining your approach +// https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ +// Time complexity :O(n) +// Space complexity : O(1) +// Did this code successfully run on Leetcode : yes +class Solution { + + public int removeDuplicates(int[] nums) { + int i = 1; + int count = 1; + int j = 1; + while(j2){ + j++; + continue; + } + }else{ + count = 1; + } + nums[i] = nums[j]; + i++; + j++; + } + return i; + } +} \ No newline at end of file diff --git a/Search2DMatrix.java b/Search2DMatrix.java new file mode 100644 index 00000000..21ec3e76 --- /dev/null +++ b/Search2DMatrix.java @@ -0,0 +1,21 @@ +// https://leetcode.com/problems/search-a-2d-matrix-ii/ +// Time complexity : O(m+n) where m is number of rows and n is number of columns +// Space complexity : O(1) +// Did this code successfully run on Leetcode : yes +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int row = matrix.length; + int col = matrix[0].length; + int i = 0; + int j = col-1; + while(i<=row-1 && j>=0){ + if(matrix[i][j]==target) return true; + else if(matrix[i][j]>target){ + j--; + }else{ + i++; + } + } + return false; + } +} \ No newline at end of file