Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions 3sum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Time Complexity : O(n^2)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Explaination : We use a two-pointer approach after sorting the array to find all unique triplets that sum to zero.

class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
List<List<Integer>> result = new ArrayList<>();
for(int i=0;i<n;i++){
if(i!=0 && nums[i]==nums[i-1]) continue;
if(nums[i]>0) break;
int low=i+1, 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;
}
}
24 changes: 24 additions & 0 deletions container_most_water.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : yes
// Explaination : We use two pointers to calculate the area and
// move the pointer with smaller height to find the maximum area.
class Solution {
public int maxArea(int[] height) {
int n = height.length;
int l =0;
int r = n-1;
int max=0;
while(l<r){
int curr = Math.min(height[l],height[r]);
int area = curr*(r-l);
max= Math.max(max,area);
if(height[l]<=height[r]){
l++;
}else{
r--;
}
}
return max;
}
}
29 changes: 29 additions & 0 deletions sort_colors.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Explaination : We use three pointers to sort the array in-place.
class Solution {
public void sortColors(int[] nums) {
int high = nums.length-1;
int low = 0;
int mid = 0;
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 m, int l){
int temp;
temp = nums[m];
nums[m]= nums[l];
nums[l]= temp;
}
}