diff --git a/Problem34.java b/Problem34.java new file mode 100644 index 00000000..9bb9916a --- /dev/null +++ b/Problem34.java @@ -0,0 +1,31 @@ +// Time Complexity : O(n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + + +// Your code here along with comments explaining your approach +class Solution { + public void sortColors(int[] nums) { + int low = 0; int mid = 0; int high = nums.length-1; + + while(mid <= high) { + if (nums[mid] == 2) { + swap(nums, mid, high); + high--; + } else if (nums[mid] == 0) { + swap(nums, mid, low); + low++; + mid++; + } else { + mid++; + } + } + } + + private void swap(int[] nums, int x, int y) { + int temp = nums[x]; + nums[x] = nums[y]; + nums[y] = temp; + } +} \ No newline at end of file diff --git a/Problem35.java b/Problem35.java new file mode 100644 index 00000000..c4c5c2c5 --- /dev/null +++ b/Problem35.java @@ -0,0 +1,38 @@ +// Time Complexity : O(n^2) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + + +// Your code here along with comments explaining your approach +class Solution { + public List> threeSum(int[] nums) { + Arrays.sort(nums); + int n = nums.length; + List> result = new ArrayList<>(); + + for (int i = 0; i < n; i++) { + if (i != 0 && nums[i] == nums[i-1]) continue; + if (nums[0] > 0) break; + + int low = i+1; int high = n-1; + + while(low < high) { + int sum = nums[i] + nums[low] + nums[high]; + if (sum == 0) { + result.add(Arrays.asList(nums[i], nums[low], nums[high])); + low++; + high--; + while(low < high && nums[low] == nums[low-1]) low++; + while(low < high && nums[high] == nums[high+1]) high--; + } else if (sum > 0) { + high--; + } else { + low++; + } + } + } + + return result; + } +} \ No newline at end of file diff --git a/Problem36.java b/Problem36.java new file mode 100644 index 00000000..36a06cae --- /dev/null +++ b/Problem36.java @@ -0,0 +1,32 @@ +// Time Complexity : O(n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + + +// Your code here along with comments explaining your approach +class Solution { + public int maxArea(int[] height) { + int n = height.length; + + int low = 0; int high = n-1; + int area = 0; + + while(low < high) { + int h = 0; + int w = high - low; + + if (height[low] < height[high]) { + h = height[low]; + low++; + } else { + h = height[high]; + high--; + } + + area = Math.max(area, h*w); + } + + return area; + } +} \ No newline at end of file diff --git a/Sample.java b/Sample.java deleted file mode 100644 index f5c45b5f..00000000 --- a/Sample.java +++ /dev/null @@ -1,7 +0,0 @@ -// Time Complexity : -// Space Complexity : -// Did this code successfully run on Leetcode : -// Any problem you faced while coding this : - - -// Your code here along with comments explaining your approach \ No newline at end of file