diff --git a/MergeSortedArrays.java b/MergeSortedArrays.java new file mode 100644 index 00000000..d23e1e09 --- /dev/null +++ b/MergeSortedArrays.java @@ -0,0 +1,41 @@ +import java.util.Arrays; + +// Approach 2: Two pointers + index pointer +// Time: O(m + n) +// Space: O(1) +class Solution2 { + public void merge(int[] nums1, int m, int[] nums2, int n) { + if (n == 0) { + return; + } + int p1 = m - 1; // for nums1 + int p2 = n - 1; // for nums2 + int index = m + n - 1; + while (p1 >= 0 && p2 >= 0) { + // copy the larger element to the last index + if (nums1[p1] > nums2[p2]) { + nums1[index --] = nums1[p1]; + p1 --; + } else { + nums1[index --] = nums2[p2]; + p2 --; + } + } + // copy the remaining elements in nums2 to nums1 + while (p2 >= 0) { + nums1[index --] = nums2[p2 --]; + } + } +} + +// Approach 1: Copy n elements to nums1 array from m index and sort the nums1 array +// Time: n + (m + n)log(m + n) ~= (m + n)log(m + n) +// Space: O(1) +class Solution1 { + public void merge(int[] nums1, int m, int[] nums2, int n) { + for (int i = m, j = 0; i < m + n; i ++, j ++) { + nums1[i] = nums2[j]; + } + Arrays.sort(nums1); + } +} \ No newline at end of file diff --git a/RemoveDuplicates.java b/RemoveDuplicates.java new file mode 100644 index 00000000..ec45cbad --- /dev/null +++ b/RemoveDuplicates.java @@ -0,0 +1,25 @@ +// Approach: Slow and fast pointers +// Time: O(N) +// Space: O(1) +class Solution { + private static final int MAX_DUPLICATES = 2; + public int removeDuplicates(int[] nums) { + int slow = 0; + int fast = 0; + int count = 0; + while (fast < nums.length) { + if (fast != 0 && nums[fast] == nums[fast - 1]) { + count ++; // increase count + } else { + count = 1; // reset count + } + if (count <= MAX_DUPLICATES) { + // copy elements + nums[slow] = nums[fast]; + slow ++; + } + fast ++; + } + return slow; // size of the resultant array + } +} \ No newline at end of file diff --git a/Search2dMatrix.java b/Search2dMatrix.java new file mode 100644 index 00000000..b036f7eb --- /dev/null +++ b/Search2dMatrix.java @@ -0,0 +1,29 @@ +// Time: O(m + n); m = matrix.length and n = matrix[0].length +// Space: O(1) +/** + * Start at either [0, n - 1] or [m - 1, 0] where they have one smaller neighbor and one larger neighbor. + * If target is smaller than current element then move to the smaller neighbor's index + * else move to the larger neighbor's index. + * Stop when the element is found and return true. + * If indices go out of bounds return false. + */ +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int row = matrix.length - 1; + int column = 0; + while (row >= 0 && column < matrix[0].length) { + System.out.println("matrix[row][column] = " + matrix[row][column]); + if (matrix[row][column] == target) { + return true; + } + if (target > matrix[row][column]) { + // move right + column ++; + } else { + // move up + row --; + } + } + return false; // target does not exist in the matrix + } +} \ No newline at end of file